sagelearnai

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

  1. Once a part contains letter c, it must stretch at least to the last occurrence of c.
  2. Sweep left to right, extending the current part's end to last[ch] for each character you see. When i == end, cut.

Approach

  1. last[ch] = the final index of each character.
  2. Sweep with start and end: end = max(end, last[s[i]]). When i == end, the current part is closed, so record end − start + 1 and set start = 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 res
JavaScript 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;
}