Partition Labels - Problem

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.

Input & Output

Example 1 — Basic Partitioning
$ Input: s = "ababcbaca"
Output: [4,5]
💡 Note: The string can be partitioned into "abab" and "cbaca". The first partition contains all 'a' and 'b' characters, while the second contains all 'c' characters and remaining 'a's.
Example 2 — Simple Case
$ Input: s = "eccbbbbdec"
Output: [10]
💡 Note: All characters appear throughout the string, so we cannot partition it further. The entire string must be one partition of length 10.
Example 3 — Maximum Partitions
$ Input: s = "abcdef"
Output: [1,1,1,1,1,1]
💡 Note: Each character appears only once, so we can partition into 6 parts, each containing exactly one character.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of lowercase English letters

Visualization

Tap to expand
Partition Labels - Greedy Approach INPUT String s = "ababcbaca" a b a b c b a c a 0 1 2 3 4 5 6 7 8 Last Occurrence Index Char Last a 8 b 5 c 7 Length = 9 ALGORITHM STEPS 1 Find Last Index Store last occurrence of each character 2 Track End Boundary end = max(end, last[s[i]]) Expand partition as needed 3 Check Partition End If i == end, partition is complete 4 Record Size Add (i - start + 1) to result, update start Trace Example: i=0: a, end=max(0,8)=8 i=3: b, end=max(8,5)=8 i=8: a, i==end, size=9-0=9 Wait! Let's check again... FINAL RESULT Partitioned String: abab Size: 4 cbaca Size: 5 Output: [4, 5] Verification: Partition 1: "abab" Contains: a, b (indices 0-3) Partition 2: "cbaca" Contains: c, b, a (indices 4-8) OK - Valid Partition! Key Insight: The greedy approach works by tracking the FARTHEST position each character appears. When we reach an index equal to the current partition's end boundary, all characters in that partition have their last occurrence within the partition. Time: O(n), Space: O(1) - only 26 letters to track. TutorialsPoint - Partition Labels | Greedy Approach
Asked in
Amazon 45 Google 35 Facebook 28 Microsoft 22
269.4K Views
High Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen