15% off all plans & roadmaps Use code

See plans

Sort Colors

Updated

TL;DR: Sort an array of 0s, 1s and 2s in place without a library sort. Keep three pointers that split the array into a 0 zone, a 2 zone and an unknown middle, and sort it in one pass with O(1) extra space.

Problem

You are given an array nums with n objects colored red, white, or blue. Sort the array in place so that objects of the same color sit next to each other, ordered red, then white, then blue.

The integers 0, 1, and 2 stand for red, white, and blue. You must solve the problem without calling the library sort function.

Example 1

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

Example 2

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

Constraints

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

Constraints that matter

  • nums[i] is only 0, 1 or 2. With three possible values you do not need a comparison sort. Counting or partitioning beats O(n log n).
  • The array must be sorted in place. Building a second sorted array is not allowed, so you need swaps or overwrites inside nums.
  • n is at most 300, so even an O(n^2) bubble sort passes. The limit is small on purpose, so the interview is about whether you spot the three-value structure.
  • n is at least 1, so you never receive an empty array. A single element is already sorted and every loop must handle it without an index error.

View on LeetCode

Hints

Hint 1

The pattern is two pointers with in-place partitioning.

Hint 2

Treat the problem as plain sorting and write bubble sort.

Solution

Intuition

The pattern is two pointers with in-place partitioning. Look at the values: only three exist. A general sort compares elements against each other, but here every element can be classified on its own. A 0 belongs at the front, a 2 belongs at the back, and a 1 belongs in between.

Picture a clerk sorting a line of coats into two racks at the ends and a pile in the middle. The low pointer is the next free spot on the front rack, and high is the next free spot on the back rack.

That suggests splitting the array into four zones: finished 0s on the left, finished 1s next, an unknown zone, and finished 2s on the right. You keep a pointer at each border. Every step looks at one unknown element and moves it across a border, which shrinks the unknown zone by one.

This works because the borders only move in one direction and each move settles one element for good. Nothing is ever revisited once it sits in a finished zone. That gives one pass and no extra memory.

The one subtle part is what you swap in. When you send a 2 to the back, the element you pull from the back is unknown. You must inspect it before moving on. When you send a 0 to the front, the element you pull from the front is always a 1 or the same cell, so it is already classified.

Watch the pattern animation

Worked example

Input: nums = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Explanation: The array holds two 0s, two 1s and two 2s. After sorting in place, both 0s come first, then both 1s, then both 2s.

Approach 1: Brute force: repeated adjacent swaps

Treat the problem as plain sorting and write bubble sort. Scan the array, and whenever a neighbor pair is out of order, swap it. Repeat the full scan until a scan makes no swaps.

This is correct for any values, which is why a beginner reaches for it. It ignores that only three values exist.

Steps

  1. Set a flag swapped to true to enter the loop.
  2. Reset swapped to false at the start of each scan.
  3. Walk i from 0 to n - 2 and compare nums[i] with nums[i + 1].
  4. If nums[i] is larger, swap the two and set swapped to true.
  5. Stop when a full scan finishes with no swaps.

Dry run

Trace on [2,0,2,1,1,0]. Each line is the array after one full scan.

  • Scan 1: [0,2,1,1,0,2]. The last 2 bubbled to the end.
  • Scan 2: [0,1,1,0,2,2].
  • Scan 3: [0,1,0,1,2,2].
  • Scan 4: [0,0,1,1,2,2].
  • Scan 5: no swaps happen, so the loop stops with [0,0,1,1,2,2].

Complexity

TimeO(n^2)
SpaceO(1)

Here n is the array length, and each scan costs n - 1 comparisons. Every swap removes exactly one inversion (an out-of-order pair), and an array has at most n * (n - 1) / 2 inversions, so the number of scans is at most n. That gives O(n^2) time. Only a few integer variables are used, so space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        n = len(nums)
        swapped = True
        while swapped:
            swapped = False
            for i in range(n - 1):
                if nums[i] > nums[i + 1]:
                    nums[i], nums[i + 1] = nums[i + 1], nums[i]
                    swapped = True

Approach 2: Counting sort, two passes

What's slow: bubble sort compares neighbors again and again and moves values one cell at a time. It pays for generality the input does not need.

The insight that fixes it: with only three values, the sorted array is fully described by how many 0s, 1s and 2s exist. Count them in one pass, then overwrite the array from the left with that many 0s, then 1s, then 2s.

Steps

  1. Create counts = [0, 0, 0].
  2. Pass 1: for each value x in nums, increment counts[x].
  3. Set a write index idx to 0.
  4. Pass 2: for each color c from 0 to 2, write c into nums[idx] and advance idx, repeating counts[c] times.
  5. Return with no value, since nums is already updated.

Dry run

Trace on [2,0,2,1,1,0].

  • Pass 1 reads each value: counts go [0,0,1], [1,0,1], [1,0,2], [1,1,2], [1,2,2], [2,2,2].
  • Pass 2 writes two 0s into indices 0 and 1, two 1s into indices 2 and 3, and two 2s into indices 4 and 5.
  • The array becomes [0,0,1,1,2,2], which matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Here n is the array length. Pass 1 touches each element once, and pass 2 writes each of the n cells exactly once, so total work is 2n, which is O(n). The counts array has three cells no matter how large n gets, so extra space is O(1). It uses two passes, which is why the follow-up asks for something tighter.

PythonTested in our runner

from typing import List

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        counts = [0, 0, 0]
        for x in nums:
            counts[x] += 1
        idx = 0
        for color in range(3):
            for _ in range(counts[color]):
                nums[idx] = color
                idx += 1
In-place Array Modification pattern infographic for Sort Colors

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 3: One-pass three pointers (Dutch national flag)OptimalIn-place Array Modification

What's slow: counting sort reads the data once and then rewrites it in a second pass. The counts throw away the elements, so you must rebuild them from scratch.

The insight that fixes it: place each element into its final zone the moment you see it. Keep low as the next cell for a 0, high as the next cell for a 2, and mid as the element under inspection. Cells before low are 0s, cells from low up to mid - 1 are 1s, and cells after high are 2s. Cells from mid to high are unknown.

Why it is correct. The loop keeps one invariant: cells before low hold 0s, cells from low to mid minus one hold 1s, and cells after high hold 2s. Each step either grows a finished zone or shrinks the unknown range while keeping that invariant true. When mid passes high, every cell is classified, so the array is sorted.

Steps

  1. Set low = 0, mid = 0, high = n - 1.
  2. Loop while mid <= high.
  3. If nums[mid] is 0, swap it with nums[low], then increment both low and mid.
  4. If nums[mid] is 1, leave it and increment mid.
  5. If nums[mid] is 2, swap it with nums[high] and decrement high. Do not move mid, because the swapped-in value is unchecked.
  6. When mid passes high, the unknown zone is empty and the array is sorted.

Dry run

Trace on [2,0,2,1,1,0], with n = 6. The array column shows the state after the step.

Steplowmidhighnums[mid]ActionArray after
start0052swap with index 5, high--[0,0,2,1,1,2]
10040swap with itself, low++, mid++[0,0,2,1,1,2]
21140swap with itself, low++, mid++[0,0,2,1,1,2]
32242swap with index 4, high--[0,0,1,1,2,2]
42231mid++[0,0,1,1,2,2]
52331mid++[0,0,1,1,2,2]
end243-mid > high, stop[0,0,1,1,2,2]

In the first row the 0 from index 5 landed at mid and was handled on the next step, which is why mid waits after a 2. The final array matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Here n is the array length. Every loop iteration either increases mid by one or decreases high by one, and the loop ends when they cross. The gap high - mid + 1 starts at n and shrinks by one each iteration, so there are at most n iterations of constant work. Only three integer pointers are stored, so space is O(1).

PythonTested in our runner

from typing import List

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        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:
                # the value from high is unchecked, so mid stays
                nums[mid], nums[high] = nums[high], nums[mid]
                high -= 1

Common mistakes

  • Writing mid += 1 after swapping with high. The value that arrives from the back has never been inspected and may be a 0. Keep mid in place and only decrement high.
  • Using while mid < high as the loop condition. When mid == high, one unknown cell is still left. Use mid <= high.
  • Forgetting low += 1 after the 0 case. The 0 zone never grows, and the next 0 overwrites the one you placed earlier. Advance both low and mid.
  • Not advancing mid in the 0 case. The swapped-in value from low is always a 1 (or the same cell), so it is already classified. Skipping mid += 1 makes the loop revisit it.
  • Initializing high = len(nums) instead of len(nums) - 1. The first swap then reads past the end of the array. Start at the last valid index.
  • Calling nums.sort() or building a new list and returning it. The problem bans the library sort and wants nums changed in place. A new list assigned to a local name leaves the caller's array untouched.

Edge cases

  • [0]: a single element is already sorted. The loop runs once, increments low and mid, and exits.
  • [2,2,2]: every step is a swap to high. high falls to -1 and the array is unchanged.
  • [0,0,0] or [1,1,1]: only one color. Pointers sweep through without moving data in a harmful way.
  • [2,1,0]: fully reversed. The first step swaps 2 and 0 to give [0,1,2], then the 1 and the 2 are accepted in place.
  • [1,0] and [1,2]: two elements with a 1 first. Check that mid does not run past high after the 1 is skipped.
  • Already sorted input such as [0,1,2]: the algorithm still completes in one pass and leaves the array as is.

Follow-ups interviewers ask

Can you do it in one pass with constant extra space?
Yes, that is the three-pointer approach. Each iteration moves exactly one element into its final zone, so you read the array once and use three integers. Counting sort needs two passes because it reads first and writes second.
What if there were k colors instead of 3?
Counting sort generalizes with a counts array of size k, giving O(n + k) time and O(k) space. A one-pass in-place partition for more than three colors does not extend cleanly with a single swap rule. You can run the three-way partition recursively, or use a standard sort in O(n log n).
Why does swapping with low never bring in an unchecked value?
Everything from low up to mid - 1 has already been inspected and is a 1. So when low is behind mid, nums[low] is a 1. When low equals mid, you swap a cell with itself. In both cases the value moving to mid needs no further check, so mid can advance.

Sort Colors FAQ

What is the time complexity of Sort Colors?

The one-pass three-pointer solution runs in O(n) time and O(1) space. Each loop iteration either advances mid or retreats high, and they meet after at most n iterations. Bubble sort is O(n^2) and counting sort is O(n) with two passes.

Why use two pointers for Sort Colors?

Two pointers at the ends of the unknown region let you place 0s at the front and 2s at the back with one swap each. A third pointer scans the middle. This sorts the three values in a single pass without extra memory.

Can Sort Colors be solved in O(1) extra space?

Yes. Both counting sort (three counters) and the three-pointer partition use constant extra space. Only the three-pointer version does it in a single pass.

Why does mid not move when nums[mid] is 2?

The swap pulls an unseen value from the high end into mid. That value could be a 0, 1 or 2. You need to examine it on the next iteration, so mid stays put.

Is the Sort Colors solution in Python different from Java?

The logic is identical. Python swaps with tuple assignment, Java uses a temporary variable. Neither language has an overflow risk here because values are only 0, 1 or 2.

Why is this called the Dutch national flag algorithm?

The three zones of 0s, 1s and 2s resemble the three bands of the Dutch flag. Dijkstra described the partitioning problem with that name. LeetCode 75 is a direct application of it.

Asked at

See which companies ask this — Pro

Practise it