You are given an array whose entries are only the integers 0, 1, and 2, where each value stands for a color: red, white, and blue respectively. Rearrange the array in place so that every 0 comes first, then every 1, and finally every 2, keeping identical colors grouped together.
Solve it without leaning on a library sorting routine, and ideally in a single pass over the data using constant extra space.
Example 1
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
All the reds move to the front, the whites to the middle, and the blues to the end.
Example 2
Input: nums = [2,0,1]
Output: [0,1,2]
Constraints
1 ≤ nums.length ≤ 300nums[i] is one of 0, 1, or 2See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI