Two Pointers
LC #75Medium
Sort Colors
Two Pointers
MetaMicrosoftGoogleAmazonAppleProblem
Sort an array of 0s, 1s, and 2s in-place in one pass without using a sort function (Dutch National Flag problem).
arraytwo-pointerssorting
Constraints
- ›n == nums.length
- ›1 ≤ n ≤ 300
- ›nums[i] is 0, 1, or 2
- ›In-place, O(1) space, one-pass preferred
Example
Input
nums = [2, 0, 2, 1, 1, 0]Output
[0, 0, 1, 1, 2, 2]Why
Dutch National Flag: 0s, then 1s, then 2s. In-place.