Sort Colors

Problem Id: 75 Difficulty: Medium Tag: Array Tag: Two Pointers Tag: Sort


Intuition

We would need 3 pointers during the loop to mark the spliter of 0, 1 and 2.

Solution


class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        hi0 = hi1 = 0
        for hi2, num in enumerate(nums):
            nums[hi2] = 2
            if num < 2:
                nums[hi1] = 1
                hi1 += 1
            if num < 1:
                nums[hi0] = 0
                hi0 += 1