75. Sort Colors
Sorting Colors in Python: A Step-by-Step Guide
In this blog post, we'll dive into a common problem known as the "Dutch National Flag problem." The goal is to sort an array containing three distinct integers representing colors. Specifically, we'll sort an array of colors where 0, 1, and 2 represent red, white, and blue, respectively. We'll use a simple counting approach to achieve this.
Problem Statement
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.
The Solution
We'll use a dictionary to count the occurrences of each color and then overwrite the original array based on these counts.
Step-by-Step Explanation
Step 1: Initialize a Dictionary with Counts
We start by initializing a dictionary using dict.fromkeys([0, 1, 2], 0)
to store the count of each color.
count = dict.fromkeys([0, 1, 2], 0)
Step 2: Count the Occurrences of Each Color
Next, we iterate through the input array nums
and update the dictionary with the count of each color.
n = len(nums)
for i in range(n):
count[nums[i]] += 1
Step 3: Extract the Counts
After counting the occurrences, we extract the counts of 0s, 1s, and 2s from the dictionary for easier access.
count_0 = count[0]
count_1 = count[1]
count_2 = count[2]
Step 4: Overwrite the Array
Now, we iterate through the array again and overwrite it with the sorted order of colors.
for i in range(n):
if i < count_0:
nums[i] = 0
elif i < count_0 + count_1:
nums[i] = 1
else:
nums[i] = 2
Full Code
from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
count = dict.fromkeys([0, 1, 2], 0)
n = len(nums)
for i in range(n):
count[nums[i]] += 1
count_0 = count[0]
count_1 = count[1]
count_2 = count[2]
for i in range(n):
if i < count_0:
nums[i] = 0
elif i < count_0 + count_1:
nums[i] = 1
else:
nums[i] = 2
Complexity Analysis
- Time Complexity: O(n) – Counting occurrences takes O(n) time, and overwriting the array also takes O(n) time.
- Space Complexity: O(1) – The extra space used for the dictionary is constant.
Conclusion
This approach ensures an efficient solution with linear time complexity and constant space complexity. By counting the occurrences of each color and then overwriting the array, we achieve the desired order of red, white, and blue colors.
Additional Resources
For an alternative approach, check out this LeetCode solution by Bikash Kumar.
Comments
Post a Comment