Skip to content

Sort Colors

Solve on LeetCodeMedium
Time
Space

You are given an array nums with n objects coloured red, white, or blue. Sort them in-place so that objects of the same colour are adjacent, with the colours in the order red, white, and blue.

We use the integers 0, 1, and 2 to represent the colours red, white, and blue respectively.

You must solve this problem without using the library’s sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation: The array has two 0s, two 1s and two 2s; sorted in place the 0s come first, then the 1s, then the 2s.

Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]

Constraints:

  • n == nums.length
  • 1≤n≤3001 \le n \le 300
  • nums[i] is either 0, 1, or 2.

Follow-up: Could you come up with a one-pass algorithm using only constant extra space?

A counting sort (count the 0s, 1s and 2s, then overwrite the array) already runs in O(n)O(n), but it needs two passes. The follow-up asks for one.

Because there are only three values, we can instead grow three bands at the same time while scanning once — the Dutch national flag partition. Keep three pointers so that at every moment:

RangeContents
[0, lo)all 0
[lo, mid)all 1
[mid, hi]not yet examined
(hi, n)all 2

Look at nums[mid] and move it into the band it belongs to. The unknown region shrinks by one element at each step, so the scan ends after at most n steps.

  1. Set lo = 0, mid = 0, hi = n - 1.
  2. While mid <= hi:
    • If nums[mid] == 0: swap nums[lo] and nums[mid], then increment both lo and mid. The value swapped in from lo is a 1 (or it is the same cell), so it is safe to step past it.
    • If nums[mid] == 1: it is already in the middle band; increment mid.
    • If nums[mid] == 2: swap nums[mid] and nums[hi], then decrement hi. Do not advance mid: the value that came from hi has not been examined yet.

Green cells are final, blue is the element being examined:

  1. Dutch national flag partition on [2,0,2,1,1,0], step 1 of 8
  2. Dutch national flag partition on [2,0,2,1,1,0], step 2 of 8
  3. Dutch national flag partition on [2,0,2,1,1,0], step 3 of 8
  4. Dutch national flag partition on [2,0,2,1,1,0], step 4 of 8
  5. Dutch national flag partition on [2,0,2,1,1,0], step 5 of 8
  6. Dutch national flag partition on [2,0,2,1,1,0], step 6 of 8
  7. Dutch national flag partition on [2,0,2,1,1,0], step 7 of 8
  8. Dutch national flag partition on [2,0,2,1,1,0], step 8 of 8
8 steps. Swipe or scroll to move between them.
  • Time: O(n)O(n) — each iteration either advances mid or decrements hi, so there are at most n iterations, all in a single pass.
  • Space: O(1)O(1) — three indices.
  • Single element or all the same colour: the loop only moves mid (or only hi) and the array is left unchanged.
  • Already sorted / reverse sorted: handled identically; no special casing is needed.

Think before you peek

Work out an approach on your own first — the explanation will still be here when you want it.

class Solution {
public:
void sortColors(vector<int>& nums) {
int lo = 0, mid = 0, hi = (int)nums.size() - 1;
while (mid <= hi) {
if (nums[mid] == 0) {
swap(nums[lo++], nums[mid++]);
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums[mid], nums[hi--]);
}
}
}
};
class Solution {
public void sortColors(int[] nums) {
int lo = 0, mid = 0, hi = nums.length - 1;
while (mid <= hi) {
if (nums[mid] == 0) {
swap(nums, lo++, mid++);
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums, mid, hi--);
}
}
}
private void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
class Solution:
def sortColors(self, nums: list[int]) -> None:
lo, mid, hi = 0, 0, len(nums) - 1
while mid <= hi:
if nums[mid] == 0:
nums[lo], nums[mid] = nums[mid], nums[lo]
lo += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[hi] = nums[hi], nums[mid]
hi -= 1

Give it a try first

Attempt the problem on LeetCode — the code will still be here.