LeetCode #763 Medium

Partition Labels

Split a string into the most parts so each letter appears in at most one part.

stringgreedyhash-table
Open on LeetCode ↗
02

Intuition

Cutting whenever a character changes fails because that character may reappear much later. Once a partition contains a character, it must extend through that character's final occurrence. While scanning, the farthest last occurrence of every character seen in the current partition defines the earliest safe boundary. Closing exactly at each safe boundary greedily maximizes the number of parts.

How to spot this pattern

If each value must belong to only one segment, determine every value's full occurrence span. A greedy sweep can close a segment when all spans opened inside it have ended.

03

Approach

1

Record the final index of every character

Scan the string once and overwrite last[char] with its index. This lookup tells how far a partition must extend after including that character.

2

Grow the current required boundary

During a second scan, update end to the maximum of its current value and the current character's last index. New characters inside the range may push the boundary farther right.

3

Cut at the earliest safe position

When the scan index equals end, all characters in the current segment finish there or earlier. Append its length and begin the next segment after that index.

04

Solution

1class Solution:
2 def partitionLabels(self, s: str) -> List[int]:
3 last = {char: i for i, char in enumerate(s)}
4 sizes = []
5 start = 0
6 end = 0
7 for i, char in enumerate(s):
8 end = max(end, last[char])
9 if i == end:
10 sizes.append(end - start + 1)
11 start = end + 1
12 return sizes
05

Common pitfalls

Cutting at the current character's last index only

✗ Wrong
end = last[char]
✓ Right
end = max(end, last[char])

An earlier character in the partition may require a later boundary.

Computing the wrong segment length

✗ Wrong
sizes.append(end - start)
✓ Right
sizes.append(end - start + 1)

Both boundary indices belong to the partition.

Starting the next segment at the boundary

✗ Wrong
start = end
✓ Right
start = end + 1

The boundary character was already included in the completed segment.

06

Edge cases

All characters are distinct

Every last occurrence equals its current index, producing one-character partitions.

One character fills the string

Its last occurrence extends the first partition to the final index.

Nested occurrence ranges

The running maximum absorbs every inner range before a cut is made.

07

Complexity

Time
O(n)
Space
O(1)
The lowercase alphabet bounds the last-occurrence table to constant size.