Python O(n) 1 pass in-place solution with explanation

  • 16

    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
                nums[white], nums[blue] = nums[blue], nums[white]
                blue -= 1

  • 1

    Why don't you increment white pointer when you swap with blue pointer? (else case)

  • 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.

  • 0

    @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.

  • 0

    @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.

  • 0

    @IWantToPass Have a look at the diagrams here to get a better understanding of it.

  • 0

    @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)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.