Algo-Sim › Two Pointers

Sort Colors

Medium · Two Pointers · step through it in Java, Python and C++ on your own input

Sort an array of 0s, 1s, and 2s in place in a single pass (Dutch national flag).

Problem

The array nums holds only the values 0, 1 and 2 (think red, white, blue). Sort it in place so all 0s come first, then the 1s, then the 2s, without calling a library sort.

Constraints

Edge cases to test

Follow-up questions

Why does mid not advance after swapping with high?
The value swapped in from high has not been looked at yet, so it must be checked before moving on.
What about k colours?
Counting sort: two passes, O(n + k) time and O(k) space. The three-way partition is the k = 3 case done in one pass.

Solution

Java

public void sortColors(int[] nums) {
    int low = 0, mid = 0, high = nums.length - 1;
    while (mid <= high) {
        if (nums[mid] == 0) {
            swap(nums, low, mid);
            low++;
            mid++;
        } else if (nums[mid] == 1) {
            mid++;
        } else {
            swap(nums, mid, high);
            high--;
        }
    }
}

private void swap(int[] nums, int i, int j) {
    int tmp = nums[i];
    nums[i] = nums[j];
    nums[j] = tmp;
}

Python

def sort_colors(nums):
    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:
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void sortColors(vector<int> &nums) {
        int low = 0, mid = 0, high = int(nums.size()) - 1;
        while (mid <= high) {
            if (nums[mid] == 0) {
                swap(nums, low, mid);
                low++;
                mid++;
            } else if (nums[mid] == 1) {
                mid++;
            } else {
                swap(nums, mid, high);
                high--;
            }
        }
    }

    void swap(vector<int> &nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
};

More Two Pointers problems