SDE & MLE Prep

75. Sort Colors

Problem

nums holds only 0s, 1s and 2s (red, white, blue). Sort it in place so all 0s come first, then 1s, then 2s, without a library sort.

Example: [2,0,2,1,1,0] → [0,0,1,1,2,2]

Constraints: follow-up: one pass with O(1) extra space.

Dutch national flag: lo = next slot for 0, hi = next slot for 2, i scans. Swap 0s to the front, 2s to the back (don't advance i after swapping with hi, since the swapped-in value is unexamined).

[2 0 2 1 1 0]
 lo/i       hi   2 -> swap with hi, hi--
 ...
result [0 0 1 1 2 2]   regions: [0..lo) = 0, [lo..i) = 1, (hi..] = 2

Complexity: O(n) one pass, O(1) space.

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        lo, i, hi = 0, 0, len(nums) - 1
        while i <= hi:
            if nums[i] == 0:
                nums[lo], nums[i] = nums[i], nums[lo]
                lo += 1; i += 1
            elif nums[i] == 2:
                nums[hi], nums[i] = nums[i], nums[hi]
                hi -= 1
            else:
                i += 1