Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Greedy

Partition Labels

MEDIUM✓ CHIP-TIMEDLC #763 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Cut a string into the maximum number of contiguous pieces so that no letter spills across a cut — every occurrence of a letter must stay inside a single piece. Report each piece's length in order.

A string of letters needs to be sliced into contiguous pieces, reading left to right, so that no single letter has occurrences spread across two different pieces — every appearance of a letter must live inside one piece.

The goal is finding the maximum number of pieces the string can be split into under that rule, in the order the pieces appear, and reporting how long each piece is.

Pieces are read off in order and cover the whole string with no character skipped or reused — the lengths reported should sum back to the string's total length.

  • the string uses lowercase letters only
  • every occurrence of a letter must stay confined to a single piece
  • pieces are reported in left-to-right order, covering the whole string
  • piece lengths always sum to the total length of the input string
EX 01
s = "abac"
→ [3, 1]
a's last occurrence pulls b into the first piece
EX 02
s = "abcabc"
→ [6]
every letter repeats at the far end — one piece
EX 03
s = "aaaa"
→ [4]
single repeated letter, one piece

The hintstake only what you need

HINT 1 THE NUDGE

A cut can only happen where nothing forces the piece open further. What would tell you a piece can't possibly end yet?

HINT 2 THE STRUCTURE

Track, for the current open piece, the farthest-right position any letter inside it is still going to reappear. The piece can't close before that position.

HINT 3 ONE STEP FROM THE ANSWER

Precompute each letter's last index in one pass. Walk the string extending the current piece's boundary to the max last-index seen so far; the moment your walk reaches that boundary, cut.

Coach's boardthe pattern, step by step

THE LAST-INDEX WALKPATTERN · GREEDY — LAST-INDEX MAPs = "abac"
a
b
a
c
LAST INDEX OF EACH LETTER
a → 2
b → 1
c → 3
STEP 1

Precompute each letter's last index: a→2, b→1, c→3. Now walk left to right, stretching the current piece to the farthest last-index seen.

STEP 1 / 8 · ← → WORK TOO

The splitstwo paces, two languages

grind/partition-labels.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last = {c: i for i, c in enumerate(s)}
        result = []
        start = end = 0
        for i, c in enumerate(s):
            end = max(end, last[c])
            if i == end:
                result.append(end - start + 1)
                start = i + 1
        return result
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 11 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED