Problem overview
The method partitionLabels receives a string s of lowercase letters. Cut it into as many parts as possible so that each letter appears in only one part. The parts keep the letters in order, so joining them gives s back. The method returns a list with the size of each part, from left to right.
For s = "noonlevelradar" the answer is [4, 5, 5], with the parts "noon", "level" and "radar". No letter shows up in two of them. A cut inside "noon" would put one n on each side. For "mississippi" the answer is [1, 10]: the m appears once, so it stands alone, while the first i is at index 1 and the last one is the final letter, so "ississippi" cannot be cut. For "world", every letter is unique and the answer is [1, 1, 1, 1, 1].
The lesson asks for O(n) time, with up to 100,000 letters.
Approach: extend the part to cover each letter's last copy
Trying every set of cut positions is exponential. Think about the first part instead. It starts at index 0 and contains the first letter, so it must also contain the last copy of that letter. But every letter between those two spots belongs to the part now, and each of them drags in its own last copy, which may be even further right. The part ends at the first index where nothing inside it has a copy further right.
That suggests two passes:
- Record the last index of every letter.
- Walk through the string keeping
end, the furthest last-copy index of any letter in the current part. When the current index reachesend, nothing in the part appears later, so a cut is safe.
Cutting as early as possible is also what gives the most parts: a later cut would only swallow letters that could have started their own parts.
Step by step
- Create
last = [0] * 26. One slot per letter: slot 0 fora, slot 1 forband so on. - First pass: loop with
ioverrange(len(s)). - Store the index:
last[ord(s[i]) - ord('a')] = i.ordgives a character's code, and the codes ofatozare consecutive, so the subtraction gives 0 foraup to 25 forz. A laterioverwrites an earlier one, so after the loop each slot holds the last index of its letter. - Create
sizes = []for the answer. - Create
start = 0, where the current part begins. - Create
end = 0, the furthest index the current part must reach. - Second pass: loop with
ioverrange(len(s))again. - Grow the part:
end = max(end, last[ord(s[i]) - ord('a')]). The part holding this letter must hold its last copy. - Check for a cut:
if i == end. - Record the size: append
end - start + 1tosizes. Both ends are included, hence the+ 1. - Start the next part right after this one:
start = i + 1. - Return
sizes. At the last indexendcannot be larger thani, so the loop always finishes with a cut.
For "noonlevelradar", the first pass gives these last indexes:
a: 12 d: 11 e: 7 l: 8 n: 3 o: 2 r: 13 v: 6
The second pass then goes like this:
0 n end 3
1 o end 3
2 o end 3
3 n end 3 cut
4 l end 8
5 e end 8
6 v end 8
7 e end 8
8 l end 8 cut
9 r end 13
10 a end 13
11 d end 13
12 a end 13
13 r end 13 cut
The cuts happen at indexes 3, 8 and 13, so the sizes are 4, 5 and 5.
The solution in Python
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = [0] * 26
for i in range(len(s)):
last[ord(s[i]) - ord('a')] = i
sizes = []
start = 0
end = 0
for i in range(len(s)):
end = max(end, last[ord(s[i]) - ord('a')])
if i == end:
sizes.append(end - start + 1)
start = i + 1
return sizes
Python details worth knowing:
[0] * 26builds a list of 26 zeros. That is safe here because integers are immutable; the same trick with a list of lists would share one inner list.- Strings in Python are immutable and indexable, so
s[i]is a one-character string, andordturns it into its code. - The two loops are separate on purpose. The second one needs the final
lasttable, so it cannot start until the first pass has seen the whole string.
Complexity
Time: O(n). Two passes over the string, with constant work per character.
Space: O(1) besides the answer. The table has 26 slots whatever the length of the string. The returned list holds one number per part.
Edge cases and common mistakes
- A string of one letter.
"a"gives[1]. - One letter repeated across the whole string.
"abcab"gives[5]: theaat index 0 reaches index 3, thebinside it reaches index 4, and the part cannot end earlier. - Cutting at the first copy of a letter. A table of first indexes says nothing about where a letter shows up again, so a part could end before the later copies of its letters. The table must hold last indexes.
- Forgetting
+ 1in the size. A part from indexstartto indexendholdsend - start + 1letters. - Forgetting to reset
start. The next part must begin ati + 1, or later sizes grow too large.
Testing
Results from running the method:
| s | Result |
|---|---|
"noonlevelradar" | [4, 5, 5] |
"mississippi" | [1, 10] |
"world" | [1, 1, 1, 1, 1] |
"abcab" | [5] |
"a" | [1] |
