Partition Labels
Cut a string into as many parts as possible so that each letter appears in only one part.
The problem
You get a string s of lowercase letters. Split it into as many parts as possible so that every letter appears in at most one part, keeping the parts in their original order. Return the lengths of the parts.
Input s = "abacdeedfg"
Output [3, 1, 4, 1, 1]
The parts are aba, c, deed, f and g. The a's must share a part, and so must the d's and the e's.
Input s = "chaichai"
Output [8]
Every letter appears in both halves, so the whole string is one part.
Key constraint: Only the last position of each letter matters, and there are just 26 letters.
How to spot the pattern
- Each letter's first and last positions form a range, and overlapping ranges must stay in the same part.
- You want as many cuts as possible, so you cut as soon as it is safe.
The idea
A part that contains a letter must stretch to that letter's last position. So walk the string keeping end, the farthest last position of any letter in the current part. When your index reaches end, every letter in the part has finished, so you can cut there, and cutting at the earliest safe point gives the most parts.
Brute force: Try each cut position and compare the letters on both sides of it, which takes O(n^2) time.
Step by step
- 1Record the last index of every letter.
- 2Walk the string with a
startand anendfor the current part, both at 0. - 3At each index
i, setend = max(end, last[s[i]]). - 4When
i == end, addend - start + 1to the answer and start the next part ati + 1. - 5Return the list of lengths.
See the pattern move
The greedy pattern on a small example. Step through it, or press play.
Code
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = {ch: i for i, ch in enumerate(s)} # last position of each letter
sizes = []
start = end = 0
for i, ch in enumerate(s):
end = max(end, last[ch]) # this part must reach the last copy of ch
if i == end:
# every letter seen in this part ends here, so it is safe to cut
sizes.append(end - start + 1)
start = i + 1
return sizesComplexity
Time
O(n)
Space
O(1)
Two passes over the string; the table of last positions has 26 entries.
Watch out for
- Cutting when you reach the current letter's last position, instead of the largest last position seen in the part.
- Returning the parts themselves instead of their lengths.
Follow-up questions
How is this related to Merge Intervals?
Each letter's first and last positions form an interval, and merging the overlapping intervals gives exactly the parts. The greedy pass does that merge without building the intervals.
What if the string could hold any characters?
Store the last positions in a hash map instead of an array of 26; the pass stays the same.
In Hinglish
Har letter ki aakhri position yaad rakho. Part ko tab tak badhao jab tak usme aaye har letter ki last position cover na ho jaye, phir wahin kaat do.