You are given a string s of lower-case letters. Cut it into consecutive pieces so that every letter lives in exactly one piece: if a letter shows up in a piece, all of its copies in s must be in that same piece.
Make as many pieces as you can, and return their lengths from left to right. Gluing the pieces back together in order must give s again.
Example 1
Input: s = "abacdcefge" Output: [3, 3, 4] Why: the pieces are "aba", "cdc" and "efge"; no letter crosses a cut
2 more examples and the constraints
Example 2
Input: s = "abacdd" Output: [3, 1, 2] Why: "aba", "c" and "dd": the c can stand alone
Example 3
Input: s = "zxyxz" Output: [5] Why: the two z's hold the whole string together
Constraints
- 1 ≤ length of s ≤ 500
sholds only the lettersatoz
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Merge letter spansO(n)
- Greedy scan with last positionsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 500 characters | Verdict |
|---|---|---|---|
| Merge letter spans | O(n) | Passes; a classic merge | |
| Greedy scan with last positions | O(n) | Best; two short loops |
n = length of s. Both are linear; the greedy one skips building the spans.
Edge cases to test
- One character. "q" is one piece of length 1.
- All letters different. "abcdef" can be cut after every letter: [1, 1, 1, 1, 1, 1].
- First and last letters match. "abcda" cannot be cut at all: the two a's force one piece of 5.
- A later letter stretches the piece. In "kabcdekfgfh" the piece starts with k, and the second k at index 6 pulls the cut past b, c, d and e.
Common mistakes
- Cutting when the current letter's own last index is reached, instead of the largest last index seen in the piece.
- Returning the pieces themselves, or their start positions, instead of their lengths.
- Forgetting the final piece in the span-merging version, which is only closed after the loop.
How to talk through it
- 1Clarify. Only lower-case letters? Do I return lengths, in order from left to right?
- 2Reframe as spans. Each letter covers first to last index. A cut is legal only where no span crosses it.
- 3Merge, then simplify. Merging spans works. Then say you can merge on the fly with a single
endpointer. - 4Code the greedy scan. Build the last-index map, then stretch
endand cut wheni == end. Say why the earliest cut is safe. - 5Test out loud. Try "abcdef", "abcda" and Example 2, where a single letter forms its own piece.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?