Sort Colors (Dutch Flag)

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Sort Colors (Dutch Flag)

Approach

Use three pointers: low tracks the boundary for 0s, high tracks the boundary for 2s, and mid scans through. When mid finds a 0, swap with low and advance both. When mid finds a 2, swap with high and only decrement high. When mid finds a 1, just advance mid.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Dutch National Flag

Why It Works

The three pointers partition the array into four regions: 0s (before low), 1s (low to mid), unprocessed (mid to high), and 2s (after high). Each swap places an element in its correct region.

Updated Mar 2026