Back to Dashboard
Dutch National Flag Problem
MediumProblem Statement
Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array.
The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists of three different numbers that is why it is called Dutch National Flag problem.
Examples
Example 1:
- Input:
nums = [2,0,2,1,1,0] - Output:
[0, 0, 1, 1, 2]
Approach 1: Two Pointers
O(n)
O(1)
class Solution {
public void sortColors(int[] nums) {
var low = 0;
var high = nums.length - 1;
for (int i = 0; i <= high;) {
var val = nums[i];
if (val == 0) {
swap(nums, i, low);
low ++;
i ++;
} else if (val == 2) {
swap(nums, i, high);
high --;
} else {
i ++;
}
}
}
private void swap(int[] nums, int x, int y) {
var t = nums[x];
nums[x] = nums[y];
nums[y] = t;
}
}