Three-Way Color Partition
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Tests the ability to partition an array into three distinct categories using a single-pass, constant-space algorithm.
Problem Statement
You have an array of color-coded items where each item is labeled with one of three values: 0, 1, or 2. Your task is to rearrange the array in-place so that all items with the same label appear together, ordered as 0s first, then 1s, then 2s.
You must accomplish this in one linear scan through the array without using extra space proportional to the input size.
Function Signature
def three_way_partition(items: List[int]) -> List[int]:
"""
Partitions items in-place into three groups: 0s, 1s, and 2s.
Returns the modified list.
"""
Constraints
0 <= len(items) <= 10^5- Each element in
itemsis either 0, 1, or 2 - You must sort in-place with O(1) extra space
- Your solution must run in O(n) time with a single pass through the data
Notes
- The function modifies the input list in-place and returns it
- When the array is already partitioned correctly, no changes are needed
- Empty arrays and single-element arrays require no modifications
Examples
Example 1
Input: three_way_partition([2, 0, 1, 2, 1, 0])
Output: [0, 0, 1, 1, 2, 2]
Example 2
Input: three_way_partition([1, 2, 0])
Output: [0, 1, 2]
Hints
Hint 1
Think about maintaining boundaries between three regions as you scan through the array
Hint 2
You'll need to track where the next 0 should go, where the next 2 should go, and which element you're currently examining
Hint 3
When you encounter a 2 and swap it to the end, don't advance your current position—you haven't examined what you just swapped in yet
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires a three-way partitioning strategy. We maintain three pointers that divide the array into four sections:
- [0 ... left-1]: all 0s (finalized)
- [left ... current-1]: all 1s (finalized)
- [current ... right]: unexamined elements
- [right+1 ... end]: all 2s (finalized)
We start with left = 0, current = 0, and right = len(items) - 1. The entire array is initially unexamined.
As we scan, we inspect items[current]:
-
If it's 0: Swap it with
items[left]. Since the element atleftis either a 1 (from the middle region) or also a 0 (whenleft == current), we can safely advance bothleftandcurrent. -
If it's 1: It belongs exactly where it is. Just advance
current. -
If it's 2: Swap it with
items[right]and decrementright. Crucially, we do NOT advancecurrentbecause the element we just swapped in from positionrighthas not been examined yet—it could be a 0, 1, or 2.
The loop continues while current <= right. Once current surpasses right, the unexamined region is empty and the array is fully partitioned.
Why It Works
The correctness relies on maintaining the four-region invariant at every step. Each swap places an element into its final region:
- Swapping a 0 to
leftextends the 0s region - Leaving a 1 at
currentextends the 1s region - Swapping a 2 to
rightextends the 2s region
The key insight is asymmetry: after placing a 0, we know the swapped-in element (from the 1s region) is safe to skip over, but after placing a 2, we must re-examine what we pulled in from the unknown region.
Complexity
-
Time: O(n) — We make exactly one pass through the array. Each element is examined at most once, and each swap moves at least one element to its final region.
-
Space: O(1) — Only three integer pointers are used. All rearrangement happens in-place.
Solution Code
from typing import List
def three_way_partition(items: List[int]) -> List[int]:
left = 0
current = 0
right = len(items) - 1
while current <= right:
if items[current] == 0:
items[left], items[current] = items[current], items[left]
left += 1
current += 1
elif items[current] == 1:
current += 1
else: # items[current] == 2
items[current], items[right] = items[right], items[current]
right -= 1
return items