Sort Colors — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Sort an array of 0s, 1s, and 2s in place without using a library sort.” The two-pass counting sort is obvious — but the one everyone remembers is the Dutch National Flag algorithm: a single-pass, O(1) space solution using three pointers.
The Problem
Given an array nums with objects colored red (0), white (1), or blue (2), sort them in place so same-colored objects are adjacent, in order 0, 1, 2.
Example
Input: nums = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Dutch National Flag | Do you know the three-pointer algorithm? |
| Pointer invariants | Can you state what each pointer represents? |
| Loop termination | Do you use mid <= high (not < high)? |
| One-pass vs. two-pass | Can you optimize from counting sort to DNF? |
Step 1: The Key Insight
Three pointers maintain three regions: low marks the 0-boundary, high marks the 2-boundary, mid scans. When nums[mid] is 0, swap to low and advance both. When 2, swap to high and retreat high only (don’t advance mid — the swapped value is unseen). When 1, advance mid.
---
Python Implementation
def sortColors(nums: list[int]) -> None:
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
# Don't increment mid — swapped value needs examination
Time & Space Complexity
| Aspect | Complexity |
|---|---|
| Time | O(n) — single pass |
| Space | O(1) — in place |
Common Interview Mistakes
- Incrementing
midafter swapping withhigh. The value fromhighis unseen — don’t skip it. - Using
mid < highinstead ofmid <= high. When equal,nums[mid]is still unsorted. - Proposing a general sort. Use the constrained value set — that’s the point.
What a Strong Candidate Sounds Like
“I’ll use the Dutch National Flag algorithm. Three pointers:
low,mid,high. Everything left oflowis 0, betweenlowandmidis 1, right ofhighis 2. When I see a 0, swap to left and advance both. When 2, swap to right and retreathighonly. One pass, O(1) space.”
Related Problems to Practice
- Two Sum — Array manipulation fundamentals.
- Container With Most Water — Two-pointer pattern.
- 3Sum — Multi-pointer array traversal.
Practice This in a Mock Interview
Start a mock interview for Sort Colors on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub