Intuition
There are only three possible values — 0, 1, and 2 — so we don't need a comparison sort. If we know how many of each color we have, we can paint the array back in order.
Explanation
Approach
- First pass: count the occurrences of
0,1, and2. - Second pass: overwrite
nums— firstc0zeros, thenc1ones, thenc2twos.
Walk-through
nums = [2, 0, 2, 1, 1, 0] → counts {0: 2, 1: 2, 2: 2} → write [0, 0, 1, 1, 2, 2].
Complexity
- Time:
O(n)— two linear passes. - Space:
O(1)— three integer counters.
Implementation
import java.util.*;
class Solution {
public int[] sortColors(int[] nums) {
int[] counts = new int[3];
for (int x : nums) counts[x]++;
int i = 0;
for (int color = 0; color < 3; color++) {
for (int c = 0; c < counts[color]; c++) {
nums[i] = color;
i++;
}
}
return nums;
}
}