← Back to Algorithms, page 1

algorithms-0016 · Medium mid

Sort colours (Dutch national flag): sort a list containing only 0, 1 and 2 in a single pass and in place.

Keep three regions with pointers low, mid and high: everything before low is 0, between low and mid is 1, after high is 2, and mid scans the unknown part. A 0 is swapped to low, a 1 is skipped, and a 2 is swapped to high without advancing mid, because the value swapped in has not been checked. One pass, O(n) time, O(1) space.

Full answer

Problem

Given nums with values only 0, 1 or 2, sort it in place in one pass without using a library sort.

Example: [2, 0, 2, 1, 1, 0] becomes [0, 0, 1, 1, 2, 2].

Constraints: 1 <= len(nums) <= 300 (the approach scales to any size), O(1) extra space.

Brute force

Counting sort: count the 0s, 1s and 2s in one pass, then overwrite the list in a second pass. O(n) time and O(1) space, but two passes. A library sort is O(n log n).

Optimal approach

Pointers: low = 0, mid = 0, high = n - 1. While mid <= high:

  • nums[mid] == 0: swap with nums[low], then low += 1, mid += 1.
  • nums[mid] == 1: mid += 1.
  • nums[mid] == 2: swap with nums[high], then high -= 1 only.

Why it works

The invariant is nums[:low] are 0, nums[low:mid] are 1, nums[mid:high + 1] are unknown, nums[high + 1:] are 2. Each step shrinks the unknown region by one and keeps the invariant:

  • Swapping a 0 to low moves a known 1 (or the same element when low equals mid) to mid, so both pointers can advance.
  • Swapping a 2 to high brings in an unknown value, so mid must stay and check it.

When the unknown region is empty, the list is sorted.

Complexity

O(n) time, one pass, O(1) extra space.

Code

python
def sort_colors(nums):
    """Dutch national flag: sort a list of 0s, 1s and 2s in one pass, in place.

    Invariant: nums[:low] are 0, nums[low:mid] are 1, nums[high+1:] are 2.
    """
    low, mid, high = 0, 0, len(nums) - 1
    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1                 # do not advance mid: the swapped-in value is unchecked
    return nums


if __name__ == "__main__":
    assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]
    assert sort_colors([2, 0, 1]) == [0, 1, 2]
    assert sort_colors([]) == []
    assert sort_colors([1]) == [1]
    assert sort_colors([2, 2, 2]) == [2, 2, 2]
    assert sort_colors([2, 1, 0, 0, 1, 2, 0]) == [0, 0, 0, 1, 1, 2, 2]
    print("all tests passed")

Save as a16_sort_colors.py and run python3 a16_sort_colors.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list. All the same value. Already sorted or reverse sorted. A 2 swapped with another 2 (handled because mid is not advanced).

Pattern

Three-way partitioning. Quicksort uses it to handle many equal keys (elements less than, equal to and greater than the pivot), and it solves "move negatives before positives" style problems.

python
def sort_colors(nums):
    """Dutch national flag: sort a list of 0s, 1s and 2s in one pass, in place.

    Invariant: nums[:low] are 0, nums[low:mid] are 1, nums[high+1:] are 2.
    """
    low, mid, high = 0, 0, len(nums) - 1
    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1                 # do not advance mid: the swapped-in value is unchecked
    return nums


if __name__ == "__main__":
    assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]
    assert sort_colors([2, 0, 1]) == [0, 1, 2]
    assert sort_colors([]) == []
    assert sort_colors([1]) == [1]
    assert sort_colors([2, 2, 2]) == [2, 2, 2]
    assert sort_colors([2, 1, 0, 0, 1, 2, 0]) == [0, 0, 0, 1, 1, 2, 2]
    print("all tests passed")

Single-pass three-pointer partition with the invariant written in the docstring.

Complexity

Time: O(n). Space: O(1). Each iteration either advances mid or moves high left, so the loop runs at most n times.

By level

Fresher: Gives the counting solution and then the three-pointer loop, tracing it on the example. Should be able to trace the three pointers on a short list.

Mid: States the invariant and justifies each pointer move, linking it to quicksort partitioning. Explains why the middle pointer does not advance after a swap with the high end.

Senior: Generalises to k-way partitioning, discusses stability and cache behaviour, and when a counting approach is simpler to maintain. Can state the number of swaps in the worst case.

Key points

  • Three regions: 0s before low, 1s between low and mid, 2s after high
  • Swap 0s to low and advance both
  • Swap 2s to high and do not advance mid
  • One pass, O(1) space
  • Same idea as three-way quicksort partition

Common mistakes

  • Advancing mid after swapping with high
  • Using mid < high and missing the last element
  • Counting then rewriting when one pass was required
  • Forgetting the empty list

Follow-ups

  • How does three-way partitioning improve quicksort with many duplicates?
  • How would you sort k colours?
  • Can you make it stable?

Tips

  • Write the invariant before the code
  • Explain the asymmetry between the 0 and 2 cases
  • Mention counting sort as the two-pass baseline

Evaluation rubric

  • Correct one-pass algorithm
  • Clear invariant
  • Explains why mid does not advance on a 2
  • Correct complexity