Link: 75. Sort Colors
Track: Amazon Tag
Question
Restate the problem
- Given an integer array
numscontaining only0,1, and2, - Sort the array in-place so that all
0s come first, then1s, then2s - Without using built-in sort
- have negtive number
Edge Case
[-1, -1, -1]nums = []- already sorted
Method 1 - Counting
Method 2 - Dutch National Flag (Three pointers, One-pass)
Method 2 - Dutch National Flag (Three pointers, One-pass)
Approach
- Use three pointers to partition the array in one pass:
left: next position to place0mid: current index scanning the arrayright: next position to place2
Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
Code
class Solution:
def sortColors(self, nums: List[int]) -> None:
left, right = 0, len(nums) - 1
mid = 0
while mid <= right:
if nums[mid] == 0:
nums[mid], nums[left] = nums[left], nums[mid]
mid += 1
left += 1
elif nums[mid] == 1:
mid += 1
elif nums[mid] == 2:
nums[mid], nums[right] = nums[right], nums[mid]
right -= 1
# mid += 1History
- Feb-15-2026 Peeked
- wrong approach