Three-Bucket Rearrangement With Constant Extra Space
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests in-place three-way partitioning of an array holding only 0, 1 and 2 using constant extra space and a single linear pass, with careful pointer invariants.
Group the Labels
A warehouse scanner tags each parcel with a label that is one of 0, 1, or 2. You are given the tags as a list labels.
Reorder the list in place so that every 0 appears first, then every 1, then every 2. The function must also return the same list object once it has been rearranged.
Requirements
- Change the input list itself rather than building a new one.
- Use only
O(1)additional memory. - Aim for a solution that finishes in a single left-to-right sweep, running in
O(n)time. - The relative order of equal values is irrelevant, since equal values are indistinguishable.
- An empty list is valid and should be returned unchanged.
Constraints
0 <= len(labels) <= 10^5- Each element of
labelsis exactly0,1, or2. - The returned list must contain the same multiset of values as the input, arranged in non-decreasing order.
Examples
Example 1
Input: group_labels([2, 0, 2, 1, 1, 0])
Output: [0, 0, 1, 1, 2, 2]
Example 2
Input: group_labels([0, 1, 2])
Output: [0, 1, 2]
Example 3
Input: group_labels([2, 2, 1, 1, 0, 0])
Output: [0, 0, 1, 1, 2, 2]
Example 4
Input: group_labels([1, 0, 1, 2, 0, 2, 1])
Output: [0, 0, 1, 1, 1, 2, 2]
Hints
Hint 1
Think of the list as split into four zones: confirmed 0s on the left, confirmed 1s next, a not-yet-inspected middle, and confirmed 2s on the right. Which pointers mark the boundaries?
Hint 2
Inspect the element at the start of the unknown zone. If it is 0, swap it into the 0 zone; if it is 1, just grow the 1 zone; if it is 2, swap it to the end of the unknown zone.
Hint 3
After swapping with the right boundary, the value that arrives at your current position has not been inspected yet, so do not advance the current pointer in that case. Loop while the current index is less than or equal to the right boundary.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a three-way partition (the Dutch National Flag idea). Keep three indices that divide the list into four regions:
[0 .. zero_end-1] -> all 0s
[zero_end .. cur-1] -> all 1s
[cur .. two_start] -> not yet examined
[two_start+1 .. n-1] -> all 2s
At the start, zero_end = cur = 0 and two_start = n - 1, so everything is unexamined. While cur <= two_start, look at labels[cur]:
- 0: swap it with
labels[zero_end], then advance bothzero_endandcur. - 1: it already belongs in the 1 region, so advance
cur. - 2: swap it with
labels[two_start]and decrementtwo_start. Do not advancecur.
Why it is correct
- When swapping with
zero_end, the value that lands atcuris either the element itself (ifzero_end == cur) or a 1 from the 1 region. Either way it is already classified, so advancingcuris safe. - When swapping with
two_start, the value that lands atcurcomes from the unexamined region and could be anything, socurmust stay put to inspect it next. - Every branch keeps the four-region invariant and shrinks the unexamined region by exactly one element, so the loop ends after at most
niterations. Whencur > two_startthe unexamined region is empty, leaving 0s, then 1s, then 2s. - The loop condition must be
<=; with<the final unexamined element would be skipped.
Empty lists skip the loop entirely, and lists with a single repeated value are handled without special cases.
Complexity
- Time:
O(n), a single pass with constant work per step. - Space:
O(1), only three integer indices.
Reference solution
from typing import List
def group_labels(labels: List[int]) -> List[int]:
zero_end = 0
cur = 0
two_start = len(labels) - 1
while cur <= two_start:
if labels[cur] == 0:
labels[zero_end], labels[cur] = labels[cur], labels[zero_end]
zero_end += 1
cur += 1
elif labels[cur] == 1:
cur += 1
else:
labels[cur], labels[two_start] = labels[two_start], labels[cur]
two_start -= 1
return labels