Sort Colors Two Pointer Dutch Flag in DSA C++ - Time & Space Complexity
We want to understand how the time needed to sort colors using two pointers changes as the number of colors grows.
How does the sorting time grow when we have more colors to arrange?
Analyze the time complexity of the following code snippet.
void sortColors(std::vector<int>& nums) {
int low = 0, mid = 0, high = nums.size() - 1;
while (mid <= high) {
if (nums[mid] == 0) {
std::swap(nums[low], nums[mid]);
low++; mid++;
} else if (nums[mid] == 1) {
mid++;
} else { // nums[mid] == 2
std::swap(nums[mid], nums[high]);
high--;
}
}
}
This code sorts an array containing 0s, 1s, and 2s by moving pointers and swapping elements in one pass.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single while loop that moves the mid pointer through the array.
- How many times: The loop runs at most n times, where n is the number of elements.
As the number of colors (n) increases, the number of steps grows roughly the same as n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps grow linearly with input size; doubling input roughly doubles the work.
Time Complexity: O(n)
This means the sorting time grows directly in proportion to the number of elements.
[X] Wrong: "Because there are nested if-else checks, the time complexity is O(n²)."
[OK] Correct: The loop runs only once through the array, and each element is handled in constant time, so the total work is linear, not quadratic.
Understanding this linear time sorting method shows you can efficiently handle problems with limited value ranges using pointers, a skill valued in many coding challenges.
"What if we added a fourth color? How would the time complexity change?"
Practice
Sort Colors Two Pointer Dutch Flag algorithm?Solution
Step 1: Understand the problem context
The algorithm is designed specifically for arrays with only three distinct values: 0, 1, and 2.Step 2: Identify the algorithm's purpose
It sorts these values in one pass using two pointers, placing all 0s first, then 1s, then 2s.Final Answer:
To sort an array containing only 0s, 1s, and 2s in a single pass -> Option CQuick Check:
Sort colors = sort 0,1,2 in one pass [OK]
- Thinking it sorts any integer array
- Confusing it with general sorting algorithms
- Assuming it reverses the array
Solution
Step 1: Understand pointer roles
Low and mid start at the beginning (index 0), high starts at the end (index n-1).Step 2: Match initialization
int low = 0, mid = 0, high = n - 1; correctly initializes low and mid to 0, and high to n-1.Final Answer:
int low = 0, mid = 0, high = n - 1; -> Option BQuick Check:
Pointers start low=0, mid=0, high=end [OK]
- Setting low or mid to n-1 incorrectly
- Initializing all pointers to zero
- Confusing high pointer position
std::vector<int> nums = {2, 0, 2, 1, 1, 0};
int low = 0, mid = 0, high = nums.size() - 1;
while (mid <= high) {
if (nums[mid] == 0) {
std::swap(nums[low], nums[mid]);
low++; mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
std::swap(nums[mid], nums[high]);
high--;
}
}
for (int num : nums) std::cout << num << " ";Solution
Step 1: Trace the sorting process
Initially: {2,0,2,1,1,0} - Swap 2 and 0 at low and mid, low=1, mid=1 - mid points to 0, swap with low, low=2, mid=2 - mid points to 2, swap with high (0), high=4 - mid points to 0, swap with low, low=3, mid=3 - mid points to 1, mid++ - mid points to 1, mid++ Loop ends.Step 2: Final array after sorting
The array becomes: 0 0 1 1 2 2Final Answer:
0 0 1 1 2 2 -> Option AQuick Check:
Sorted colors output = 0 0 1 1 2 2 [OK]
- Not swapping correctly when nums[mid] == 2
- Incrementing mid after swapping with high
- Confusing pointer updates
int low = 0, mid = 0, high = n - 1;
while (mid < high) {
if (nums[mid] == 0) {
std::swap(nums[low], nums[mid]);
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
std::swap(nums[mid], nums[high]);
high--;
}
}Solution
Step 1: Analyze loop condition
The loop uses 'mid < high', which misses the case when mid equals high, leaving last element unsorted.Step 2: Correct loop condition
Changing to 'mid <= high' ensures all elements are processed including when mid equals high.Final Answer:
The loop condition should be 'mid <= high' instead of 'mid < high' -> Option DQuick Check:
Loop must cover mid == high for full sorting [OK]
- Using 'mid < high' misses last element
- Starting pointers incorrectly
- Wrong pointer increments or decrements
nums containing only 0s, 1s, and 2s, how would you modify the Dutch National Flag algorithm to count how many swaps are performed during sorting?Solution
Step 1: Understand when swaps happen
Swaps occur when nums[mid] is 0 or 2, swapping with low or high pointers respectively.Step 2: Implement swap counting
Introduce an integer counter initialized to zero, increment it inside the loop each time std::swap is called.Final Answer:
Add a counter variable and increment it each time a swap is done inside the loop -> Option AQuick Check:
Count swaps by incrementing on each swap call [OK]
- Counting pointer moves instead of swaps
- Counting swaps for 1s which are not swapped
- Counting before sorting instead of during
Ready to prove it?
Pass the test and this pattern moves unknown
