Skip to problem
←

Sort Colors (One-Pass, Constant Space)

Medium 0 attempts

You're given an array whose elements are only 0, 1, or 2. Sort it in-place in a single pass without using extra space for counting — this is a variant of the classic Dutch National Flag problem.

Function contract

Implement sortColors(nums).

Output: Modify argument 1 in place. The editor compares its final value; the function return value is ignored.

Example 1

Input
nums = [2,0,2,1,1,0]
Output
[0,0,1,1,2,2]

Example 2

Input
nums = [1]
Output
[1]
Constraints
  • 1 <= nums.length <= 1000
  • nums[i] is 0, 1, or 2

Three-Way Partitioning

The processed prefix contains zeros, the next region contains ones, and the processed suffix contains twos. The middle region remains unclassified. After swapping a two to the end, keep the middle pointer in place: the incoming value still needs inspection. Each iteration shrinks the unclassified region by one.

javascript
function sortColors(nums) {
  let lo = 0, mid = 0, hi = nums.length - 1;
  while (mid <= hi) {
    if (nums[mid] === 0) { [nums[lo], nums[mid]] = [nums[mid], nums[lo]]; lo++; mid++; }
    else if (nums[mid] === 1) mid++;
    else { [nums[mid], nums[hi]] = [nums[hi], nums[mid]]; hi--; }
  }
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript