Skip to content
DSA Patterns
Menu
Language
GreedyLC #7636 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumgreedy

Partition Labels

Problem (restated)

Partition string so each letter appears in at most one part. Return sizes of parts as large/as many as possible (greedy max parts).

Intuition

Record last index of each char. Scan left→right expanding end to last[c]; when i==end, cut a part.

Approaches

Expand to last occurrence

Unverified
Time O(n)Space O(1)

Idea. Same spirit as merge intervals on char spans.

Walkthrough. “ababcbacadefegdehijhklij” → [9,7,8].

Trade-offs. Two-pass O(n); first pass builds last[].

Solution
export function partitionLabels(s: string): number[] {
  const last = Array(26).fill(0);
  for (let i = 0; i < s.length; i++) last[s.charCodeAt(i) - 97] = i;
  const res: number[] = [];
  let start = 0, end = 0;
  for (let i = 0; i < s.length; i++) {
    end = Math.max(end, last[s.charCodeAt(i) - 97]!);
    if (i === end) {
      res.push(end - start + 1);
      start = i + 1;
    }
  }
  return res;
}
export function partitionLabels(s: string): number[] {
  const last = Array(26).fill(0);
  for (let i = 0; i < s.length; i++) last[s.charCodeAt(i) - 97] = i;
  const res: number[] = [];
  let start = 0, end = 0;
  for (let i = 0; i < s.length; i++) {
    end = Math.max(end, last[s.charCodeAt(i) - 97]!);
    if (i === end) {
      res.push(end - start + 1);
      start = i + 1;
    }
  }
  return res;
}

Template connection

last[c] is the last index of character c. One scan pushes end out to last[s[i]]. When i catches end, [start, end] is one part.

Reflection

  • Store each letter’s last index. A part grows until it has swallowed the last index of every letter already inside it.
  • abab is one part. abc is three. When a part ends, the next part starts at that index.
  • One repeated letter is a single part. The parts cut the string from start to end and do not overlap.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Partition labels of "ababcbacadefegdehijhklij". Each letter lives in at most one part.

a
0
b
1
a
2
b
3
c
4
b
5
a
6
c
7
a
8
mapa→8b→5c→7

last[c] = rightmost index

Key:CurrentActive rangeMatchSettled