Partition Labels

Cut a string into the maximum number of parts such that no letter appears in more than one part.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
two-pointers greedy string

Problem#

Partition the string into the largest number of substrings such that each letter appears in at most one substring. Return the lengths of the partitions.

Examples#

  • "ababcbacadefegdehijhklij"[9, 7, 8]
  • "eccbbbbdec"[10]

Constraints#

  • 1 <= s.length <= 500, lowercase.

Hints#

Hint 1
Pre-compute the last occurrence of each letter, then expand the current window to cover every letter in it.

Approach#

First pass: record last[c] for each letter. Second pass: scan with end = max(end, last[s[i]]). When i == end, we’ve reached a frontier no earlier letter extends past — close the partition.

Solution#

Partition Labels
class Solution {
public:
vector<int> partitionLabels(string s) {
int last[26] = {0};
for (int i = 0; i < (int)s.size(); ++i) last[s[i] - 'a'] = i;
vector<int> ans;
int start = 0, end = 0;
for (int i = 0; i < (int)s.size(); ++i) {
end = max(end, last[s[i] - 'a']);
if (i == end) {
ans.push_back(i - start + 1);
start = i + 1;
}
}
return ans;
}
};

Editorial#

The partition boundary is forced by the latest occurrence of any letter in the current segment. The window grows as we see letters whose last occurrence is further right. When i catches up to end, no letter we’ve seen so far extends past i, so it’s safe to cut — and cutting greedily here maximizes the partition count.

Complexity#

  • Time: O(n).
  • Space: O(1) (26 letters).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.