intermediate · two pointers · partition · Dutch national flag

Red, white and blue in one pass

Problem

A row of tiles is coded 0 (red), 1 (white) and 2 (blue). Rearrange it in place so all 0s come first, then all 1s, then all 2s, in a single pass and O(1) extra space.

Constraints

  • 0 ≤ n ≤ 32
  • every value is 0, 1 or 2

Examples

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

Show the solution

Three-way partition (Dutch national flag)

a[0..low) are 0s, a[low..mid) are 1s, a[mid..high] are unknown, a(high..n) are 2s. Each step shrinks the unknown region.

Why it is correct

Every branch keeps the four-region invariant; when mid passes high the unknown region is empty. After swapping with high, mid stays because the incoming value is still unknown.

Complexity

Time O(n), extra space O(1). Each iteration advances mid or retreats high: at most n iterations.

For contrast: Count each colour, then rewrite the row. That costs O(n), two passes time and O(1) space.

Edge cases

  • All one colour.
  • Empty row.

Common mistakes

  • Advancing mid after swapping with high (the swapped-in value is unchecked).
  • Looping while mid < high and missing the last element.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class SortColors
{
    /// <summary>Sorts 0s, 1s and 2s in one pass (Dutch national flag). O(n), O(1) space.</summary>
    public static void Sort(int[] tiles)
    {
        int low = 0, mid = 0, high = tiles.Length - 1;
        while (mid <= high)
        {
            if (tiles[mid] == 0)
            {
                (tiles[low], tiles[mid]) = (tiles[mid], tiles[low]);
                low++;
                mid++;
            }
            else if (tiles[mid] == 1)
                mid++;
            else
            {
                (tiles[mid], tiles[high]) = (tiles[high], tiles[mid]);
                high--; // mid stays: the tile swapped in is unchecked
            }
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/SortColors.cs

def sort_colors(tiles: list[int]) -> None:
    """Sort 0s, 1s and 2s in one pass (Dutch national flag). O(n), O(1) space."""
    low, mid, high = 0, 0, len(tiles) - 1
    while mid <= high:
        if tiles[mid] == 0:
            tiles[low], tiles[mid] = tiles[mid], tiles[low]
            low, mid = low + 1, mid + 1
        elif tiles[mid] == 1:
            mid += 1
        else:
            tiles[mid], tiles[high] = tiles[high], tiles[mid]
            high -= 1  # mid stays: the tile swapped in is unchecked

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/sort_colors.py

package dev.bekadan.dsa.problems;
 
public final class SortColors {
    private SortColors() {
    }
 
    private static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
 
    /** Sorts 0s, 1s and 2s in one pass (Dutch national flag). O(n), O(1) space. */
    public static void sort(int[] tiles) {
        int low = 0, mid = 0, high = tiles.length - 1;
        while (mid <= high) {
            if (tiles[mid] == 0) {
                swap(tiles, low++, mid++);
            } else if (tiles[mid] == 1) {
                mid++;
            } else {
                swap(tiles, mid, high--); // mid stays: the tile swapped in is unchecked
            }
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/SortColors.java

#pragma once
 
#include <cstddef>
#include <span>
#include <utility>
 
namespace bekadan::dsa::problems {
 
// Sorts 0s, 1s and 2s in one pass (Dutch national flag). O(n), O(1) space.
inline void sort_colors(std::span<int> tiles) {
    std::ptrdiff_t low = 0, mid = 0, high = std::ssize(tiles) - 1;
    const auto at = [&](std::ptrdiff_t i) -> int& { return tiles[static_cast<std::size_t>(i)]; };
    while (mid <= high) {
        if (at(mid) == 0) {
            std::swap(at(low++), at(mid++));
        } else if (at(mid) == 1) {
            ++mid;
        } else {
            std::swap(at(mid), at(high--));  // mid stays: the tile swapped in is unchecked
        }
    }
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/sort_colors.hpp