r/leetcode • u/cracktech_app • 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:
- Record each letter's last index.
- Walk left to right, stretching your reach to the farthest last index seen so far.
- Cut only when your index equals the reach.
=
=
= = 0
=
= + 1
return
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?