Python coding

Group three colors in one pass

colors holds only the values 0, 1 and 2 (think red, white and blue). Rearrange it in place so every 0 comes first, then every 1, then every 2, and return the same list.

Make a single pass that swaps values into place with O(1) extra space: no sort function, and no counting the values first to rewrite the list.

  • sort_colors([2,0,1,2,1,0]) → [0,0,1,1,2,2]
  • sort_colors([1,2,0]) → [0,1,2]
  • sort_colors([2,2,1,1,0,0]) → [0,0,1,1,2,2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Keep three boundaries: everything before lo is 0, everything after hi is 2, and mid walks through the unchecked middle.

Hint 2

A 0: swap it to lo and advance both. A 1: advance mid. A 2: swap it to hi and shrink hi, but don't advance mid.

Solution and why it works
pythonO(n) · O(1)
def sort_colors(colors: list[int]) -> list[int]:
    lo, mid, hi = 0, 0, len(colors) - 1
    while mid <= hi:
        if colors[mid] == 0:
            colors[lo], colors[mid] = colors[mid], colors[lo]
            lo += 1
            mid += 1
        elif colors[mid] == 1:
            mid += 1
        else:
            colors[mid], colors[hi] = colors[hi], colors[mid]
            hi -= 1              # keep mid: the value swapped in is still unchecked
    return colors

Four regions hold as mid scans: [0, lo) is all 0s, [lo, mid) all 1s, (hi, end] all 2s, and [mid, hi] is unchecked. Each step shrinks the unchecked part by one, so it is one pass with O(1) space. The trap: after swapping a 2 to hi, don't advance mid, because the value that arrived is still unchecked ([1, 2, 0] would end as [1, 0, 2]).

Related lab: Loops in motion