DSA Tracker

Problem

Medium

Sort Colors

A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
3
Core for
26 roles

The problem

Given an array containing objects colored red, white, or blue represented by numbers 0, 1, and 2, sort them in place so that identical colors are adjacent in the order 0, 1, and 2.

Example 1

Input
nums = [1,2,0,2,0,1]
Output
[0,0,1,1,2,2]
Why
Both 0s move to the front, the two 1s sit in the middle and the two 2s end up last.

Example 2

Input
nums = [1,0,2]
Output
[0,1,2]
Why
One of each colour, placed in the order 0, 1, 2.

Example 3

Input
nums = [0]
Output
[0]
Why
A single color element requires no reordering.

Constraints

  • 1 <= nums.length <= 300
  • nums[i] is either 0, 1, or 2

How to think about it

Updated 2026-09-29

Because only three distinct keys exist, sorting is equivalent to partitioning the array into three contiguous sections: 0s on the left, 1s in the middle, and 2s on the right. Marching a mid pointer forward while swapping 0s toward the low boundary and 2s toward the high boundary places every value into its permanent bucket in a single pass.

Approaches, worst first

  1. Two-pass counting sort

    time O(n) · space O(1)

    Count the frequencies of 0, 1, and 2 across a first pass. Overwrite the array in a second pass with the appropriate number of 0s, 1s, and 2s. Very straightforward, but requires two full traversals of the data.

  2. Dutch National Flag three-pointer partitionWrite this one

    time O(n) · space O(1)

    Maintain low = 0, mid = 0, and high = n - 1. When nums[mid] is 0, swap with nums[low] and advance both low and mid. When nums[mid] is 1, increment mid. When nums[mid] is 2, swap with nums[high] and decrement high without advancing mid.

Where people lose marks · 3
  • Advancing mid after swapping with high, which misses evaluating the unexamined element freshly swapped in from the high index.
  • Iterating the loop condition `mid < high` instead of `mid <= high`, failing to process the element located at index high.
  • Invoking built-in general comparison sort libraries, which violates the in-place linear-time one-pass partition objective.

Full solution

Dutch National Flag three-pointer partition: low/mid/high sweep the array once, swapping 0s left and 2s right in place. It is the one to write because counting sort needs two passes and a library sort is exactly what the problem forbids.

Python
def sort_colors(nums: list[int]) -> None:
    """Dutch National Flag: one pass, in place."""
    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:
            # do not advance mid: the value swapped in from high is unexamined
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1
JavaScript
function sortColors(nums) {
  // Dutch National Flag: one pass, in place.
  let low = 0;
  let mid = 0;
  let high = nums.length - 1;
  while (mid <= high) {
    if (nums[mid] === 0) {
      [nums[low], nums[mid]] = [nums[mid], nums[low]];
      low += 1;
      mid += 1;
    } else if (nums[mid] === 1) {
      mid += 1;
    } else {
      // do not advance mid: the value swapped in from high is unexamined
      [nums[mid], nums[high]] = [nums[high], nums[mid]];
      high -= 1;
    }
  }
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .