Sort Colors

Question

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

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

Note: You are not suppose to use the library's sort function for this problem.

Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

Tags

  • Array
  • Two Pointers
  • Sort

Thought

Two approaches:

  • Counting sort
  • Two pointers

For the first algorithm, count the number of elements for the array and reassign the value of the elements in the array according to the counter.

For the second algorithm, use two pointers to record the pointer for the elements 0 and 2 and one pointer to loop through the array. Swap according to the element with the index pointer in the loop.

Code

two-pass with counting sort

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        counter = collections.defaultdict(int)
        for num in nums:
            counter[num] += 1
        start = 0
        for i in xrange(3):
            size = counter[i]
            end = start + size
            nums[start:end] = [i] * size
            start = end

one-pass with two pointer

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        p0, p2 = 0, len(nums) - 1
        index = 0
        while index <= p2:
            if nums[index] == 0:
                nums[index], nums[p0] = nums[p0], nums[index]
                p0 += 1
                index += 1
            elif nums[index] == 2:
                nums[index], nums[p2] = nums[p2], nums[index]
                p2 -= 1
            else:
                index += 1

results matching ""

    No results matching ""