Sort Colors
A medium Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 3
- Core for
- 25 roles
- Platform
- LeetCode
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 = [2,0,2,1,1,0]
- Output
- [0,0,1,1,2,2]
- Why
- All 0s gather at the beginning, followed by all 1s, and ending with all 2s.
Example 2
- Input
- nums = [2,0,1]
- Output
- [0,1,2]
- Why
- The distinct colors sort into ascending numerical sequence.
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-09Because 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
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.
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;
}
}
}
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.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .