Partition Labels
Difficulty: Medium · Pattern: Greedy · LeetCode #763
Split s into as many parts as possible so that each letter appears in at most one part. Return the sizes of the parts, in order.
Examples
text
"ababcbacadefegdehijhklij" → [9,7,8] ("ababcbaca", "defegde", "hijhklij")
"eccbbbbdec" → [10]Hints
- Once a part contains letter
c, it must stretch at least to the last occurrence ofc. - Sweep left to right, extending the current part's end to
last[ch]for each character you see. Wheni == end, cut.
Approach
last[ch]= the final index of each character.- Sweep with
startandend:end = max(end, last[s[i]]). Wheni == end, the current part is closed, so recordend − start + 1and setstart = i + 1.
This is an interval-merging problem in disguise. Each letter defines an interval [first, last], and the parts are the merged, overlapping groups. O(n) time and O(26) space.
Complexity
Time: O(n). Space: O(1) (26 letters).
Python solution
def partitionLabels(s):
last = {ch: i for i, ch in enumerate(s)}
res, start, end = [], 0, 0
for i, ch in enumerate(s):
end = max(end, last[ch])
if i == end:
res.append(end - start + 1)
start = i + 1
return resJavaScript solution
function partitionLabels(s) {
const last = {};
for (let i = 0; i < s.length; i++) last[s[i]] = i;
const res = [];
let start = 0, end = 0;
for (let i = 0; i < s.length; i++) {
end = Math.max(end, last[s[i]]);
if (i === end) { res.push(end - start + 1); start = i + 1; }
}
return res;
}