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?

💡 Hint 1:
A rather straight forward solution is a two-pass algorithm using counting sort.

💡 Hint 2:
Iterate the array counting number of 0's, 1's, and 2's.

💡 Hint 3:
Overwrite array with the total number of 0's, then 1's and followed by 2's.

Submitted Code

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        front, mid, back = 0, 0, len(nums)-1

        while mid <= back:
            if nums[mid] == 0:
                nums[front], nums[mid] = nums[mid], nums[front]
                front += 1
                mid += 1
            elif nums[mid] == 1:
                mid += 1
            else:
                nums[mid], nums[back] = nums[back], nums[mid]
                back -= 1

Runtime: 0 ms | Beats 100.00%
Memory: 19.22 MB | Beats 61.96%

한 번의 순회만으로 문제를 풀기 위해서 Dutch National Flag, 즉 3개의 파티션으로 나누는 알고리즘을 사용했다.

Other Solutions

1st

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        count = {}
        for i in range(len(nums)):
            count[nums[i]] = count.get(nums[i], 0) + 1
        
        idx = 0

        for color in range(3):
            freq = count.get(color, 0)
            nums[idx : idx + freq] = [color] * freq
            idx += freq

time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)

쉽게 하려면 각 숫자의 출현 빈도를 먼저 카운팅한 후 다시 nums를 채우는 방법이 있지만 두 번 순회해야한다.

Leave a comment