Partition Labels (LeetCode 763): Solution and Explanation

Medium
Hash Table
Two Pointers
String
Greedy

Given a string, cut it into as many contiguous pieces as possible so that every letter appears in at most one piece. Return the sizes of those pieces in order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Think about the first character. Whatever piece it belongs to must extend at least as far as that character's last occurrence in the string, otherwise the letter would appear in two pieces. But every letter inside that stretch has the same requirement, so the piece may need to stretch further to cover their last occurrences too, and so on.

That suggests a simple greedy scan. Keep end, the farthest last occurrence among all letters seen in the current piece. As you move forward, each new letter may push end further out. When your index catches up to end, every letter in the piece has had its final appearance, so you can safely cut there. Cutting as early as possible is what maximizes the number of pieces, because any later cut would merge a piece that could have stood on its own. In the example "abacdc", the first piece must reach index 2 because of the second 'a', and nothing inside it reaches further, so the cut lands right after index 2.

To know each letter's last occurrence in O(1), precompute it in a first pass over the string. The second pass then needs only the running end and a counter for the current piece's length. This mirrors merging intervals: each letter defines an interval from its first to last occurrence, and the pieces are the merged groups.

Approach: Greedy scan with last-occurrence indices

  1. In a first pass, record lastIndex[c], the final position of each character.
  2. Initialize an empty result list, size = 0 and end = 0.
  3. In a second pass, for each index i and character c, increment size and set end = max(end, lastIndex[c]).
  4. When i == end, every letter in the current piece has ended, so append size to the result and reset size to 0.
  5. Return the result list.

Step-by-step example

s = "abacdc"
  1. Last occurrences: a at 2, b at 1, c at 5, d at 4.
  2. i = 0 ('a'): size = 1, end = 2. i = 1 ('b'): size = 2, end stays 2.
  3. i = 2 ('a'): size = 3, and i == end, so record 3 and reset size.
  4. i = 3 ('c'): size = 1, end = 5. i = 4 ('d'): size = 2, end stays 5.
  5. i = 5 ('c'): size = 3, and i == end, so record 3. Return [3, 3], the pieces "aba" and "cdc".

Code: Python, Java, C++

1class Solution:
2    def partitionLabels(self, s: str) -> List[int]:
3        lastIndex = {}
4        for i, c in enumerate(s):
5            lastIndex[c] = i
6            
7        res = []
8        size, end = 0, 0
9        
10        for i, c in enumerate(s):
11            size += 1
12            end = max(end, lastIndex[c])
13            
14            if i == end:
15                res.append(size)
16                size = 0
17        return res

Time and space complexity

Time

O(n)

Two passes over the string, each doing constant work per character.

Space

O(1)

The lastIndex map holds at most 26 entries for lowercase letters. The output list is not counted.

Other approaches

Merge letter intervals (time O(n), space O(1))

Build an interval from each letter's first to last occurrence, sort them by start, and merge overlapping ones exactly as in merge intervals. The sizes of the merged intervals are the answer. Same idea, more code.

Brute force cut checking (time O(n²), space O(1))

For each possible cut point, check whether any letter appears on both sides by comparing character sets of the prefix and suffix, and cut greedily at the first valid point of each remaining piece. It is easy to verify but repeats a lot of set work.

Common mistakes

  • Cutting as soon as the current character's own last occurrence is reached, without taking the max over all characters in the piece. That splits letters across pieces.
  • Forgetting to reset size after recording a piece, which makes every later size include the earlier ones.
  • Returning the pieces' end indices instead of their sizes. If you track a start index, the size is end - start + 1.
  • Recording the first occurrence instead of the last in the precomputation pass, which makes end stop too early.

Frequently asked questions

Why is the greedy approach correct for partition labels?

A piece cannot end before the last occurrence of any letter inside it, so end is the earliest legal cut. Cutting at the earliest legal point never prevents later cuts, so it produces the maximum number of pieces.

What is the time complexity of partition labels?

It is O(n) time, with one pass to record last occurrences and one pass to cut. Space is O(1) because there are only 26 letters.

How is partition labels related to merge intervals?

Each letter spans an interval from its first to its last occurrence. The pieces are exactly the groups you get by merging overlapping intervals, and the greedy scan does that merge implicitly in one pass.

Why does the answer list sizes rather than the pieces themselves?

The sizes fully describe the partition, since the pieces are contiguous and appear in order. If you need the substrings, keep a start index, slice s[start : i + 1] each time i == end, and then move start to i + 1.