AlgoInsight

DSA problem

Sort Colors

MediumQuickSort / QuickSelectPattern: QuickSort / QuickSelecttop75FreeAmazonMicrosoftGoogleMetaAppleBloomberg

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

The naive approach is to call a built-in sort routine, which runs in O(n log n) time — but the problem explicitly forbids that. A simple counting-sort variant works in two passes: first count how many 0s, 1s, and 2s the array contains, then overwrite the array with those counts. That solution is O(n) time and O(1) space, but it scans the array twice and writes every cell.

The canonical optimal approach is the Dutch National Flag algorithm, invented by Edsger Dijkstra. It partitions the array into three regions in a single pass using three pointers: low marks the boundary just past the 0s, high marks the boundary just before the 2s, and mid scans the unprocessed middle region. The invariant is that everything left of low is 0, everything between low and mid is 1, and everything right of high is 2 — the segment [mid, high] is still unknown.

At each step we inspect nums[mid]. If it is 0, we swap it with nums[low] and advance both low and mid. If it is 1, it already belongs in the middle, so we just advance mid. If it is 2, we swap it with nums[high] and decrement high only (without advancing mid), because the value that came from high has not yet been classified. The loop ends when mid > high, at which point the three regions exactly cover the array. The whole sort runs in O(n) time, makes a single pass, and uses O(1) extra space.

Examples

Example 1
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation: The three pointers partition the array as scanning proceeds. After one linear pass the 0s occupy the left, the 1s the middle, and the 2s the right.
Example 2
Input: nums = [2,0,1]
Output: [0,1,2]
Explanation: The 2 at index 0 swaps with the 1 at index 2 and high decrements; the 0 at index 0 swaps with itself and low/mid advance; the 1 stays. The final order is sorted.
Example 3
Input: nums = [0]
Output: [0]
Explanation: A single-element array is already sorted — the loop body never executes since mid > high from the start.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraytwo-pointerssortingdutch-national-flagin-place

Browse all DSA problems