Sort Colors

Given an array containing only the values 0, 1 and 2, sort it in place in a single pass without using a separate counting or sorting step.

MediumMust DoDutch National FlagTwo Pointers
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array containing only the values 0, 1 and 2, sort it in place in a single pass without using a separate counting or sorting step.

Why solve this?

The canonical three-way partition problem — it extends Segregate 0s and 1s' two boundary pointers with a third, 'current element' pointer, which is the real cognitive jump most people trip on first.

Pattern Recognition

Whenever an array holds exactly three distinct values and needs sorting in one pass without extra space, that's the Dutch National Flag signal: track a low boundary, a high boundary, and a current scanning pointer between them.

Prerequisites

  • Segregate 0s and 1s — the two-way partition this problem extends to three values.

Hints

  1. A single write pointer isn't enough here — you need three regions: confirmed 0s, unknown, and confirmed 2s.
  2. Track low (end of the 0 region), mid (current element being examined) and high (start of the 2 region).
  3. When you swap a 2 into place at high, don't advance mid — the element swapped in from high hasn't been examined yet.

Approach

Maintain three pointers: low (everything before it is a confirmed 0), high (everything after it is a confirmed 2), and mid (the element currently being classified), with mid starting at 0 and high starting at the last index. While mid <= high: if nums[mid] is 0, swap it with nums[low], then advance both low and mid, since the value now at mid (swapped from low) is already known to be 0 or 1 and safe to move past. If nums[mid] is 1, it's already in its correct region, so just advance mid. If nums[mid] is 2, swap it with nums[high] and decrement high without advancing mid — the value swapped in from high hasn't been classified yet and needs to be examined next.

Code

Solution.java
class Solution {
    public void sortColors(int[] nums) {
        int low = 0, mid = 0, high = nums.length - 1;
        while (mid <= high) {
            if (nums[mid] == 0) {
                int temp = nums[low]; nums[low] = nums[mid]; nums[mid] = temp;
                low++;
                mid++;
            } else if (nums[mid] == 1) {
                mid++;
            } else {
                int temp = nums[mid]; nums[mid] = nums[high]; nums[high] = temp;
                high--;
            }
        }
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays