Split so letters stay together
Cut a string into as many pieces as possible so that each letter appears in only one piece, by extending each piece to the last occurrence of every letter inside it. About 18 minutes.
A piece must close over its letters
Cut a string into pieces so that no letter shows up in two pieces, and make as many pieces as possible. If a piece contains the letter a, it must stretch all the way to the last a in the string, or that a would land in another piece.
So first record, for every letter, the position of its last appearance. Then every piece has a minimum size set by the letters it already holds.
Extend, then close
Scan the string with an end marker. At each position, push the end marker to the larger of itself and the last position of the current letter. Every letter inside the piece may force it longer.
When the scan reaches the end marker, nothing inside the piece appears later, so close the piece there. Record its size and start a new piece at the next position.
end = max(end, last[ch]) # the piece must reach this far
Letter a ends last at 6, so the piece stretches to at least 6.
The string is a b c. What are the piece sizes?
- A1, 1, 1
- B3
- C2, 1
Show the answer
1, 1, 1. Each letter appears once, so every letter can be its own piece.
Split into the most pieces
Given a string s of lowercase letters, cut it into as many pieces as possible so that every letter appears in at most one piece. Return the sizes of the pieces in order.
s = "ababcbacadefegdehijhklij" → [9, 7, 8]
1 ≤ s.length ≤ 100,000 · lowercase letters only