Sort Colors (Dutch National Flag Problem)
Two Pointers
Problem
Solution
class Solution:
def sortColors(self, nums: List[int]) -> None:
i=0
low = 0
high = len(nums)-1
while i <= high:
if nums[i] == 0:
t = nums[low]
nums[low] = nums[i]
nums[i] = t
low+=1
i+=1
elif nums[i] == 1:
i+=1
elif nums[i] == 2:
te = nums[high]
nums[high] = nums[i]
nums[i] = te
high-=1
#Two pointer approach: pointing two pointers at the first
#and last index of the array and have another pointer
#iterating through the array sorting the numbers in place
#Dont increment index at elif nums[i] == 2 cause we
#don't know if the swicthed number is in the right
place
#Time: O(n)
#Space: O(n)Last updated