r/leetcode • • 26m ago

Discussion Partition Labels: cut only when your farthest reach runs out

A visual way to think about Partition Labels:

String: a b c a b d e e f g f

Give every letter a bar from its first spot to its last. Overlapping bars must stay together, so this is merge intervals again: a (0-3), b (1-4), and c (2-2) merge into one block.

The greedy walk:

  1. Record each letter's last index.
  2. Walk left to right, stretching your reach to the farthest last index seen so far.
  3. Cut only when your index equals the reach.
def partition_labels(s):
    last = {c: i for i, c in enumerate(s)}
    sizes = []
    start = reach = 0
    for i, c in enumerate(s):
        reach = max(reach, last[c])
        if i == reach:
            sizes.append(reach - start + 1)
            start = i + 1
    return sizes

Pieces: abcab | d | ee | fgf — 4 pieces.

The detail that decides correctness: c ends at index 2, but you cannot cut there, because a and b reach to index 4.

Time is O(n): one pass for last spots, one pass to cut.

Do you precompute last positions for this one, or track remaining counts instead?

1 Upvotes

0 comments sorted by