Sort Colors in Python

The Sort Colors problem involves sorting an array containing only three values: 0 (red), 1 (white), and 2 (blue). We need to sort them in-place so objects of the same color are adjacent, in the order red, white, blue.

For example, if the input array is [2,0,2,1,1,0], the sorted output should be [0,0,1,1,2,2].

Algorithm: Dutch National Flag

This problem is efficiently solved using the Dutch National Flag algorithm with three pointers ?

  • Set low = 0, mid = 0, and high = length of array ? 1
  • While mid <= high:
    • If arr[mid] = 0, swap arr[mid] and arr[low], then increment both low and mid
    • If arr[mid] = 2, swap arr[high] and arr[mid], then decrement high
    • If arr[mid] = 1, just increment mid

Implementation

class Solution:
    def sortColors(self, nums):
        low = 0
        mid = 0
        high = len(nums) - 1
        
        while mid <= high:
            if nums[mid] == 0:
                nums[low], nums[mid] = nums[mid], nums[low]
                low += 1
                mid += 1
            elif nums[mid] == 2:
                nums[high], nums[mid] = nums[mid], nums[high]
                high -= 1
            else:
                mid += 1
        
        return nums

# Test the solution
solution = Solution()
colors = [2, 0, 2, 1, 1, 0]
print("Original array:", colors)
result = solution.sortColors(colors)
print("Sorted array:", result)
Original array: [2, 0, 2, 1, 1, 0]
Sorted array: [0, 0, 1, 1, 2, 2]

How It Works

The algorithm maintains three regions in the array ?

  • Region 1 (0 to low?1): Contains all 0s
  • Region 2 (low to mid?1): Contains all 1s
  • Region 3 (high+1 to end): Contains all 2s
  • Unknown region (mid to high): Elements yet to be processed

Alternative Approach Using Counting

A simpler approach is to count occurrences of each color and reconstruct the array ?

def sortColorsCount(nums):
    # Count occurrences
    count = [0, 0, 0]  # [red, white, blue]
    
    for num in nums:
        count[num] += 1
    
    # Reconstruct array
    index = 0
    for color in range(3):
        for _ in range(count[color]):
            nums[index] = color
            index += 1
    
    return nums

# Test the counting approach
colors = [2, 0, 2, 1, 1, 0]
print("Using counting approach:", sortColorsCount(colors.copy()))
Using counting approach: [0, 0, 1, 1, 2, 2]

Time and Space Complexity

Approach Time Complexity Space Complexity In-place?
Dutch National Flag O(n) O(1) Yes
Counting O(n) O(1) Yes

Conclusion

The Dutch National Flag algorithm efficiently sorts colors in a single pass with constant space. For interview purposes, this three-pointer approach demonstrates optimal problem-solving skills.

Updated on: 2026-03-25T07:47:18+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements