KatInterview

Three-Way Color Partition

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searcharraystwo-pointerssorting

Last 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 items is 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