This is a dutch partitioning problem. We are classifying the array into four groups: red, white, unclassified, and blue. Initially we group all elements into unclassified. We iterate from the beginning as long as the white pointer is less than the blue pointer.
If the white pointer is red (nums[white] == 0), we swap with the red pointer and move both white and red pointer forward. If the pointer is white (nums[white] == 1), the element is already in correct place, so we don't have to swap, just move the white pointer forward. If the white pointer is blue, we swap with the latest unclassified element.
def sortColors(self, nums): red, white, blue = 0, 0, len(nums)-1 while white <= blue: if nums[white] == 0: nums[red], nums[white] = nums[white], nums[red] white += 1 red += 1 elif nums[white] == 1: white += 1 else: nums[white], nums[blue] = nums[blue], nums[white] blue -= 1
@IWantToPass In the else case, we know the nums[white] == 2, but we don't know the value of nums[blue]. After swapping, we need to take another look at this position again.
@IWantToPass you move to the next position only if the pointer is classified. But in the else case, you don't know the value which is swapped from the blue pointer's position.
@girikuncoro Can I ask one more? Then why you can increase white by 1 in the first case, how can you be sure the one you get by swapping is 1?
Since white is moving faster than red, the one you get can only be 1 or 0? and since if 0, we will always go next, it must be 1.
@IWantToPass Have a look at the diagrams here to get a better understanding of it.
@IWantToPass I think it is because you could have swapped a 1 value into nums[white] and if that is the case you still want to swap it with the red (so you need to check it's next iteration)
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.