Sort Colors

LeetCode

LeetCode: https://leetcode.com/problems/sort-colors/

Given an array nums with n objects colored red, white, or blue (0, 1, 2), sort them in-place so that objects of the same color are adjacent.

Use the Dutch National Flag algorithm in one pass.

1def sortColors(nums: List[int]) -> None:
2 l, r = 0, len(nums) - 1
3 i = 0
4
5 while i <= r:
6 if nums[i] == 0:
7 nums[l], nums[i] = nums[i], nums[l]
8 l += 1
9 i += 1
10 elif nums[i] == 2:
11 nums[r], nums[i] = nums[i], nums[r]
12 r -= 1
13 else:
14 i += 1
l
i
2
0
0
1
2
2
1
3
1
4
r
0
5
Step 1 / 7
Step 1:
Initialize three pointers: l (next 0), i (current), r (next 2).
Pointers: i=0, l=0, r=5
Focus: select @ [0, 5]