Neetcode 150 - Partition Labels
Here is two solution for problem “Partition Labels”
1. Input, Output, Contraints
- Input:
s = "ababcbacadefegdehijhklij"
- Output:
Output: [9, 7, 8]
- Contraints:
-
1 ≤ len(s) ≤ 500
-
s consists of lowercase English letters only.
2. Dry run:
Character Last index
a 8
b 5
c 7
d 14
e 15
f 11
g 13
h 19
i 22
j 23
k 20
l 21
i s[i] last[s[i]] end=max(end,last[s[i]]) Partition
0 a 8 8
1 b 5 8
2 a 8 8
... ... ... ...
8 a 8 8 ✅ Partition [0–8] → size 9
9 d 14 14
10 e 15 15
... ... ... ...
15 e 15 15 ✅ Partition [9–15] → size 7
16 h 19 19
... ... ... ...
23 j 23 23 ✅ Partition [16–23] → size 8
✅ Output: [9, 7, 8]
3. Naive Solution - O(N^2)
class Solution:
def partitionLabels(self, s: str) -> List[int]:
res = []
i = 0
while i < len(s):
end = s.rfind(s[i]) # last index of current char
j = i
while j < end:
end = max(end, s.rfind(s[j]))
j += 1
res.append(end - i + 1)
i = end + 1
return res
⏱️ Complexity:
-
Time: O(N^2) (because of repeated rfind)
-
Space: O(1)
4. Optimal Solution — O(N)
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = {c: i for i, c in enumerate(s)}
res = []
start = end = 0
for i, c in enumerate(s):
end = max(end, last[c])
if i == end: # one partition closed
res.append(end - start + 1)
start = i + 1
return res
⏱️ Complexity
-
Time: O(N)
-
Space: O(1) (only 26 letters)
Last Updated On October 14, 2025