Reorder an array containing only 0s, 1s, and 2s so that equal values are grouped together in increasing order.
Dutch National Flag
gfgYou are given an integer array nums where each element is either 0, 1, or 2. Rearrange the array in place so that all 0s come first, followed by all 1s, and then all 2s.
Do not use built-in sorting for the main solution idea.
The goal is to produce the array in nondecreasing order while using only constant extra space if possible.
numsnums is one of 0, 1, or 2nums in place so it is sorted as 0s, then 1s, then 2s1 <= nums.length <= 300nums[i] is 0, 1, or 2Example 1
Input
nums = [2,0,2,1,1,0]
Output
[0,0,1,1,2,2]
Explanation
After rearrangement, all 0s appear first, then 1s, then 2s.
Example 2
Input
nums = [2,0,1]
Output
[0,1,2]
Explanation
The array is reordered in nondecreasing order in place.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.