Sort Colors
Problem Statement
You are given an array nums where every value is 0, 1 or 2 (think of them as red, white and blue).
Rearrange the array in place so that all the 0s come first, then all the 1s, then all the 2s.
You may not use the library sort function. The follow-up asks for a single pass with only constant extra space.
An integer array nums containing only 0, 1 and 2.
Nothing is returned. nums itself must end up as all 0s, then all 1s, then all 2s.
Two 0s, two 1s and two 2s, grouped in that order.
- β’ 1 β€ nums.length β€ 300
- β’ nums[i] is 0, 1 or 2
- β’ Follow-up: one pass, O(1) extra space
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Call a general sort; ignores that there are only 3 values
Count the 0s, 1s and 2s, then overwrite the array
low / mid / high: send 0s left, 2s right, leave 1s in the middle
The task says "sort", so sort the array with a normal comparison sort. It works, but it does not use the fact that there are only three possible values. (The problem forbids the library sort, so this is only the starting point.)
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.