📖 2 min read
Last updated on

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

SkillWhat Interviewers Observe
Dutch National FlagDo you know the three-pointer algorithm?
Pointer invariantsCan you state what each pointer represents?
Loop terminationDo you use mid <= high (not < high)?
One-pass vs. two-passCan 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.

Sorted array [0,0,1,1,2,2] with three pointers: lo (pink) at red boundary, mid (teal) scanning, hi (blue) at blue boundary. ---

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

AspectComplexity
TimeO(n) — single pass
SpaceO(1) — in place

Common Interview Mistakes

  1. Incrementing mid after swapping with high. The value from high is unseen — don’t skip it.
  2. Using mid < high instead of mid <= high. When equal, nums[mid] is still unsorted.
  3. 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 of low is 0, between low and mid is 1, right of high is 2. When I see a 0, swap to left and advance both. When 2, swap to right and retreat high only. One pass, O(1) space.”



Practice This in a Mock Interview

Start a mock interview for Sort Colors on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →