Partition Labels
MediumNeetCode 150 GreedyProblem
You are given a string s of lowercase letters. Cut it into as many consecutive pieces as possible
so that no letter appears in more than one piece.
Join the pieces back in order and you must get s again. Return the list of piece lengths.
Constraints
- 1 ≤ s.length ≤ 500
- s contains only lowercase English letters (a to z)
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: Two passes over the string with constant work per character.
Space: The last-index table holds at most 26 letters, and the output list is not counted.
First note where each letter appears for the last time. Then sweep left to right, keeping the farthest last index of any letter seen in the current piece. When the sweep reaches exactly that index, every letter in the piece is finished, so cut there and start the next piece. Cutting as early as possible gives the most pieces.