Two Pointers · Dutch flag

Sort Colors Visualizer

What is Sort Colors

The array contains only 0, 1, and 2. Group them in that order in one pass. low is the next slot for a 0, high is the next slot for a 2, and mid scans the unknown middle.

2 0 2 1 1 0
0 0 1 1 2 2

Approach

Count, then rewriteCounting the three values and rewriting the array also works. The three-pointer walk does it with swaps and no second pass over a count table.
Three regionsZeros grow from the left, twos from the right, and ones stay between them. When mid swaps with high, mid does not advance, because the new middle value has not been seen.

Interactive solution

low, mid, and high on 0, 1, and 2
low = mid = 0; high = n - 1
while mid <= high:
if a[mid] == 0: swap with low; low += 1; mid += 1
elif a[mid] == 1: mid += 1
else: swap with high; high -= 1
return a
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n)Each index is swapped at most once into a finished side.
MemoryO(1)Three indices and the same array.

Implementation

def sort_colors(a):
    low = mid = 0
    high = len(a) - 1
    while mid <= high:
        if a[mid] == 0:
            a[low], a[mid] = a[mid], a[low]
            low += 1
            mid += 1
        elif a[mid] == 2:
            a[mid], a[high] = a[high], a[mid]
            high -= 1
        else:
            mid += 1
    return a