sagelearnai

Sort Colors

Difficulty: Medium · Pattern: Two Pointers · LeetCode #75

nums contains only 0s, 1s and 2s (red, white, blue). Sort it in place so all 0s come first, then 1s, then 2s, in one pass without using a library sort. Return nothing.

Examples

text
[2, 0, 2, 1, 1, 0]  →  [0, 0, 1, 1, 2, 2]
[2, 0, 1]           →  [0, 1, 2]

Hints

  1. Counting sort (count, then overwrite) takes two passes. Can you do it in one?
  2. Keep three regions: 0s at the front, 2s at the back, unknowns in the middle.
  3. When you swap a 2 to the back, don't advance the scanning pointer, because the swapped-in value is unexamined.

Approach

Dutch national flag (Dijkstra): maintain lo (the next slot for 0), mid (the scanner) and hi (the next slot for 2). Invariant: [0, lo) are 0s, [lo, mid) are 1s, (hi, end] are 2s. If nums[mid] is 0, swap it with lo and advance both; if it's 1, advance mid; if it's 2, swap it with hi and decrement hi (without advancing mid).

Complexity

Time: O(n), one pass. Space: O(1).

Python solution
def sortColors(nums):
    lo, mid, hi = 0, 0, len(nums) - 1
    while mid <= hi:
        if nums[mid] == 0:
            nums[lo], nums[mid] = nums[mid], nums[lo]
            lo += 1; mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:
            nums[mid], nums[hi] = nums[hi], nums[mid]
            hi -= 1
JavaScript solution
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--; }
  }
}