sort-colors

Try it on leetcode

Description

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

 

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]

 

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2.

 

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Solution(Python)

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        self.threePointers(nums)
        
    # Time Complexity: O(n)
    # Space Complexity: O(1)
    def countingSort(self, nums: List[int]) -> None:
        count = [0] * 3
        
        for num  in nums:
            count[num] += 1
        
        starting_index = 0

        for c, freq in enumerate(count):
            count[c] = starting_index
            starting_index += freq
        sortedList = [0]*len(nums)
        for num in nums:
            sortedList[count[num]] = num
            count[num] += 1
        for i in range(len(nums)):
            nums[i] = sortedList[i]
            
    # Time Complexity: O(n)
    # Space Complexity: O(1)         
    def threePointers(self, nums: List[int]) -> None:
        n = len(nums)
        p1 = 0
        p2 = n-1
        cur = 0
        
        while cur <= p2:
            num = nums[cur]
            if num == 0:
                nums[cur], nums[p1] = nums[p1], nums[cur]
                cur +=1
                p1+=1
            elif num == 2:
                nums[cur], nums[p2] = nums[p2], nums[cur]
                p2-=1
            else:
                cur += 1