Partition Labels

MediumGreedyLeetCode 763 ↗World 7-13
0:00 / 0:00

Cut a string into as many pieces as possible with no letter in two pieces. Track where each letter last appears, and cut when you reach it.

▼

The problem

Given a string of lowercase letters, split it into as many parts as possible so that each letter appears in at most one part, and return the size of each part.

Example (LeetCode's): "ababcbacadefegdehijhklij" → [9, 7, 8] (parts ababcbaca, defegde, hijhklij).

def partition_labels(s):
    last = {c: i for i, c in enumerate(s)}
    sizes, start, end = [], 0, 0
    for i, c in enumerate(s):
        end = max(end, last[c])
        if i == end:
            sizes.append(end - start + 1)
            start = i + 1
    return sizes
TRY IT ON LEETCODE ▶

The solution

def partition_labels(s):
    last = {c: i for i, c in enumerate(s)}
    sizes, start, end = [], 0, 0
    for i, c in enumerate(s):
        end = max(end, last[c])
        if i == end:
            sizes.append(end - start + 1)
            start = i + 1
    return sizes

Transcript

Partition Labels. Given a string of letters, cut it into as many parts as you can, so that each letter appears in at most one part. Then return each part's size.

Here are twenty-four letters. Try a cut after the first four. It fails, because the letter A turns up again on the other side. The best you can do is three parts: nine, seven and eight letters. No letter crosses a cut.

The slow way tries every possible cut, and for each one, scans the right side for any letter from the left. That's a scan inside a loop: n squared time.

Here's the trick. First, note where each letter appears for the last time. Now walk the string. A part that holds a letter must stretch to that letter's last spot, so plant a flag there. When a new letter reaches further, push the flag. And when you reach the flag, nothing behind you looks past it, so cut. Cutting as early as you can leaves the most parts: that's the greedy choice.

In code, one pass fills a dictionary with each letter's last index. A second pass walks the string, moving end to the larger of end and that letter's last index. When the index catches up with end, the part is closed: save its size, end minus start plus one, and start the next part.

Let's run the example. The first A sets the flag at eight. B and C both end before eight, so they stay inside. At eight, cut: nine letters. D pushes the flag to fourteen, then E to fifteen. F and G stay inside. Cut: seven. Then H, I and J push it to nineteen, twenty-two and twenty-three. Cut: eight.

Two passes over the string, so the time is linear. The dictionary holds at most twenty-six letters, so the extra space is constant.

Remember each letter's last spot, push the flag, and cut when you reach it. That's Partition Labels.