Skip to content

Commit 93bceb5

Browse files
authored
Merge pull request #58 from NEHA-AMIN/feature/sort-colors
Solution #75 - Neha Amin - 13/07/2025
2 parents de37840 + 60df1f2 commit 93bceb5

File tree

3 files changed

+159
-0
lines changed

3 files changed

+159
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# 2. Sort Colors
2+
3+
**Difficulty:** *Medium*
4+
**Category:** *Arrays, Two Pointers, Sorting*
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/sort-colors/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
*Given an array nums with n objects colored red (0), white (1), or blue (2), sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.*
12+
13+
*Constraints typically include:<br>
14+
- You must solve this problem without using the library's sort function.<br>
15+
- The array contains only values 0, 1, and 2.*
16+
17+
---
18+
19+
## 💡 Approach & Key Insights
20+
21+
*The problem can be solved through various approaches. Though sorting is a valid but not expected solution, we can explore better and optimal methods by leveraging the limited number of distinct values (0, 1, 2). This allows for more efficient counting or pointer-based techniques like the Dutch National Flag algorithm.*
22+
23+
---
24+
25+
## 🛠️ Breakdown of Approaches
26+
27+
### 1️⃣ Brute Force / Naive Approach
28+
29+
- **Explanation:** *Use the built-in sorting algorithm to sort the array. This works since the array contains only 0, 1, and 2, and sorting would naturally arrange them.*
30+
- **Time Complexity:** *O(n log n) – standard sorting complexity.*
31+
- **Space Complexity:** *O(1) – assuming in-place sort.*
32+
- **Example/Dry Run:**
33+
34+
```plaintext
35+
Input: [2, 0, 2, 1, 1, 0]
36+
Sorted Output: [0, 0, 1, 1, 2, 2]
37+
```
38+
39+
---
40+
41+
### 2️⃣ Better Approach
42+
43+
- **Explanation:** *Count the number of 0s, 1s, and 2s in one pass. Then overwrite the array in a second pass by placing the right number of 0s, 1s, and 2s.*
44+
- **Time Complexity:** *O(n) – 2 passes through the array.*
45+
- **Space Complexity:** *O(1) – constant space for counters.*
46+
- **Example/Dry Run:**
47+
48+
```plaintext
49+
Input: [2, 0, 2, 1, 1, 0]
50+
Step 1: Count → count_0 = 2, count_1 = 2, count_2 = 2
51+
Step 2: Overwrite:
52+
[0, 0, 1, 1, 2, 2]
53+
```
54+
55+
---
56+
57+
### 3️⃣ Optimal Approach
58+
59+
- **Explanation:** *Use the Dutch National Flag algorithm with three pointers (low, mid, high). Rearrange elements in a single pass.*
60+
- **Time Complexity:** *O(n) – single pass.*
61+
- **Space Complexity:** *O(1) – in-place.*
62+
- **Example/Dry Run:**
63+
64+
```plaintext
65+
Input: [2, 0, 2, 1, 1, 0]
66+
Initial: low = 0, mid = 0, high = 5
67+
68+
Step-by-step:
69+
mid = 0, nums[mid] = 2 → swap(nums[mid], nums[high]) → high--
70+
mid = 0, nums[mid] = 0 → swap(nums[low], nums[mid]) → low++, mid++
71+
mid = 1, nums[mid] = 0 → swap(nums[low], nums[mid]) → low++, mid++
72+
mid = 2, nums[mid] = 2 → swap(nums[mid], nums[high]) → high--
73+
mid = 2, nums[mid] = 1 → mid++
74+
mid = 3, nums[mid] = 1 → mid++
75+
76+
Final Output: [0, 0, 1, 1, 2, 2]
77+
```
78+
79+
---
80+
81+
## 📊 Complexity Analysis
82+
83+
| Approach | Time Complexity | Space Complexity |
84+
| ---------------- | --------------- | ---------------- |
85+
| Brute Force | O(n log n) | O(1) |
86+
| Counting | O(n) | O(1) |
87+
| Dutch Flag (Optimal) | O(n) | O(1) |
88+
89+
---
90+
91+
## 📉 Optimization Ideas
92+
93+
*The Dutch National Flag algorithm is already optimal — it solves the problem in a single traversal with constant space. No further optimization is necessary.*
94+
95+
---
96+
97+
## 📌 Example Walkthroughs & Dry Runs
98+
99+
```plaintext
100+
Example:
101+
Input: [2, 0, 1]
102+
Initial: low = 0, mid = 0, high = 2
103+
104+
1. nums[mid] = 2 → swap(nums[mid], nums[high]) → [1, 0, 2], high--
105+
2. nums[mid] = 1 → mid++
106+
3. nums[mid] = 0 → swap(nums[low], nums[mid]) → [0, 1, 2], low++, mid++
107+
108+
Output: [0, 1, 2]
109+
```
110+
111+
---
112+
113+
## 🔗 Additional Resources
114+
115+
- [Dutch National Flag Algorithm](https://en.wikipedia.org/wiki/Dutch_national_flag_problem)
116+
- [Python list sorting](https://docs.python.org/3/howto/sorting.html)
117+
118+
---
119+
120+
Author: Neha Amin <br>
121+
Date: 19/07/2025
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
void sortColors(vector<int>& nums) {
4+
int low = 0, mid = 0, high = nums.size() - 1;
5+
while (mid <= high) {
6+
if (nums[mid] == 0) {
7+
swap(nums[low], nums[mid]);
8+
low++;
9+
mid++;
10+
} else if (nums[mid] == 1) {
11+
mid++;
12+
} else {
13+
swap(nums[mid], nums[high]);
14+
high--;
15+
}
16+
}
17+
}
18+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution(object):
2+
def sortColors(self, nums):
3+
"""
4+
:type nums: List[int]
5+
:rtype: None Do not return anything, modify nums in-place instead.
6+
"""
7+
low = 0
8+
mid = 0
9+
high = len(nums) - 1
10+
11+
while mid <= high:
12+
if nums[mid] == 0:
13+
nums[low], nums[mid] = nums[mid], nums[low]
14+
low += 1
15+
mid += 1
16+
elif nums[mid] == 1:
17+
mid += 1
18+
else:
19+
nums[mid], nums[high] = nums[high], nums[mid]
20+
high -= 1

0 commit comments

Comments
 (0)