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
- 1 ≤ nums.length ≤ 300
- nums[i] is 0, 1 or 2
- Follow-up: one pass and O(1) extra space
Edge cases to test
- Only one colour
- Already sorted
- Reverse sorted
Follow-up questions
- Why does
midnot advance after swapping withhigh? - The value swapped in from
highhas 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 -= 1C++
#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
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)