mediumGreedyStringGreedy

Partition Labels

mediumTime: O(n)Space: O(1)

Recognize the pattern

partition string into parts where each character appears in at most one partmaximize partition counttrack last occurrence

Brute force idea

If you approach Partition Labels in the most literal way possible, you get this: Try all possible partition points. Each position is either a cut or not. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The deeper shift in Partition Labels is this: First pass: record each character's last occurrence. Second pass: expand the current partition to include the last occurrence of every character in it. When you reach the partition boundary, cut. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Partition Labels is one steady idea: If character 'a' appears at positions 2 and 8, any partition containing position 2 must also contain position 8. The partition boundary is the maximum last occurrence of any character in it. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Partition Labels is this: Greedily cutting at the first opportunity without checking if later characters force the partition to extend. The max-last-occurrence tracking handles this. The fix is usually to return to the meaning of each move, not just the steps themselves.

Greedy Pattern