DSA AnimatorDSA animations
Sort Colors LC #75 Medium Dutch National Flag
Problem

Given an array nums with n objects colored red (0), white (1), or blue (2), sort them in-place so that objects of the same color are adjacent, in the order red, white, and blue. You must solve this without using the library's sort function.

Example 1
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Constraints: n == nums.length  |  1 ≤ n ≤ 300  |  nums[i] ∈ {0, 1, 2}
Try Examples
Custom:
Approach
3-Way Partition (Dutch National Flag)
Three pointers lo, mid, hi partition the array into regions: [0..lo-1]=all 0s, [lo..mid-1]=all 1s, [hi+1..n-1]=all 2s. Sweep mid through the array: swap 0s left, 2s right, skip 1s. O(n) time, O(1) space!
Array
0 = Red 1 = White 2 = Blue
Variables
lo
—
mid
—
hi
—
nums[mid]
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
lo=0, mid=0, hi=n-1
2
nums[mid]==0 → swap(lo,mid), lo++, mid++
3
nums[mid]==1 → mid++ only
4
nums[mid]==2 → swap(mid,hi), hi-- (no mid++)
Time
O(n)
Space
O(1)
Why It Works

Invariant: [0..lo-1] all 0s, [lo..mid-1] all 1s, [hi+1..n-1] all 2s. When mid sees 0, swap with lo (known 1) — both advance. When 2, swap with hi (unknown) — only hi shrinks since new value at mid is unclassified. When 1, just advance mid.

How to solve Sort Colors

LeetCode 75 · Medium · Arrays · Pattern: Dutch National Flag

Why the obvious approach is slow

Counting the colours and rewriting the array takes two passes. A general sort is O(n log n). We can do it in one pass, with O(1) space.

The key idea

Keep three pointers: low, mid and high. Everything before low is 0, and everything after high is 2. Mid scans the unknown part in between. A 0 swaps with low and both move, a 2 swaps with high and only high moves, and a 1 just moves mid.

Remember

Three pointers split the array into 0s, unknown, and 2s. After swapping with high, check mid again.

Run the animation above on your own input, or watch the 1:27 video explanation of Sort Colors with a dry run and Java code.

More Arrays problems