DSA AnimatorDSA animations
Partition Labels LC #763 Medium Greedy Β· Intervals
Problem

Split the string s into as many parts as possible so that each letter appears in at most one part. Return a list of the part sizes. Joined back together, the parts must give s.

Example 1
Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8] ("ababcbaca", "defegde", "hijhklij")
Example 2
Input: s = "eccbbbbdec"
Output: [10]
Constraints: 1 ≀ s.length ≀ 500  |  lowercase English letters
πŸ”€ Letters
🏁 last seen
i
πŸ“€ sizes
🎨 same colour = same letter🏁 last place that letter appears current part (stretches to cover its letters)βœ‚οΈ cut
Variables
i
β€”
letter Β· last
β€”
start
β€”
end
β€”
πŸ’‘ Step Logic
Press β–Ά Play or Next to begin.
βœ“
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
Record the last index of every letter 🏁
2
Sweep i: end = max(end, last[s[i]]), so the part stretches
3
If i == end: cut βœ‚οΈ, record end βˆ’ start + 1, start a new part
Time
O(n)
Space
O(1) Β· 26 letters
🧠 Why greedy is optimal

Every letter forces an interval from its first to its last appearance, and a part can't cut through any interval. This is Merge Intervals in disguise: end is the right edge of the merged interval so far. Cutting the moment i == end is the earliest legal cut, and cutting early never hurts the rest of the string, so you get the maximum number of parts.

⚠️ Edge cases

All distinct letters ("abc") β†’ every letter is its own part: [1,1,1]. First letter also last ("abca") β†’ one part covering everything. Remember to return sizes, not the strings. And start = i + 1 after each cut.