You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string "ababcc" can be partitioned into ["abab", "cc"], but partitions such as ["aba", "bcc"] or ["ab", "ab", "cc"] are invalid.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
Example 1:
Input: s = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
Example 2:
Input: s = "eccbbbbdec" Output: [10]
Constraints:
1 <= s.length <= 500s consists of lowercase English letters.Why this is a Two Pointers problem
Two pointers places one pointer at the start and one at the end of a sorted (or structured) array. The pointers move toward each other based on a comparison, eliminating candidates intelligently instead of checking all pairs.
On a sorted array, if your current pair's result is too big, move the right pointer left. Too small, move the left pointer right.
If you sort the array and fix one element, you need a partner that sums to the target. A partner too small? Move left pointer right. Too large? Move right pointer left. You never need to revisit a position — the sorted order tells you which direction to go.
From brute force to optimal — understand every step of the journey
On a sorted array, the key is that moving left right always increases the sum, and moving right left always decreases it. This monotonic relationship means each pointer decision permanently eliminates a column or row of the implicit n×n search grid — giving O(n) instead of O(n²).