Sort Colors Two Pointer Dutch Flag in DSA Go - Time & Space Complexity
We want to understand how the time needed to sort colors using the two-pointer Dutch Flag method changes as the number of colors grows.
Specifically, how does the number of steps grow when we sort an array of colors represented by 0, 1, and 2?
Analyze the time complexity of the following code snippet.
func sortColors(nums []int) {
low, mid, high := 0, 0, len(nums)-1
for mid <= high {
switch nums[mid] {
case 0:
nums[low], nums[mid] = nums[mid], nums[low]
low++
mid++
case 1:
mid++
case 2:
nums[mid], nums[high] = nums[high], nums[mid]
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: Single loop running while
mid <= high, scanning the array once. - How many times: Each element is visited at most once or twice due to swaps, but overall the loop runs at most
ntimes wherenis array length.
As the array size grows, the number of steps grows roughly in direct proportion.
| 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, meaning doubling the input roughly doubles the work.
Time Complexity: O(n)
This means the sorting takes time proportional to the number of elements, making it very efficient for this problem.
[X] Wrong: "Because there are nested swaps, the time complexity is O(n²)."
[OK] Correct: Each element is moved at most once or twice, and the loop pointer only moves forward, so the total steps stay proportional to n, not n squared.
Understanding this linear time sorting technique shows you can solve problems efficiently by clever pointer use, a skill highly valued in coding challenges and interviews.
"What if we changed the array to contain more than three colors? How would the time complexity change?"
Practice
Sort Colors Two Pointer Dutch Flag algorithm?Solution
Step 1: Understand the problem
The algorithm sorts an array containing only 0s, 1s, and 2s representing colors.Step 2: Identify the approach
It uses three pointers (low, mid, high) to place 0s at the start, 2s at the end, and 1s in the middle in one pass.Final Answer:
Use three pointers to separate 0s, 1s, and 2s in one pass -> Option AQuick Check:
Three pointers = One pass sorting [OK]
- Thinking it uses multiple passes like bubble sort
- Confusing counting approach with two-pointer method
- Assuming recursion is used
Solution
Step 1: Identify pointer roles
Low and mid start at 0, high starts at last index (len(nums)-1).Step 2: Match initialization
low, mid, high := 0, 0, len(nums)-1 correctly sets low=0, mid=0, high=len(nums)-1.Final Answer:
low, mid, high := 0, 0, len(nums)-1 -> Option AQuick Check:
Pointers start at array ends and start [OK]
- Swapping low and high initialization
- Setting pointers outside array bounds
- Confusing mid pointer position
nums := []int{2, 0, 2, 1, 1, 0}
low, mid, high := 0, 0, len(nums)-1
for mid <= high {
switch nums[mid] {
case 0:
nums[low], nums[mid] = nums[mid], nums[low]
low++
mid++
case 1:
mid++
case 2:
nums[mid], nums[high] = nums[high], nums[mid]
high--
}
}
fmt.Println(nums)Solution
Step 1: Trace the loop iterations
Initially nums = [2,0,2,1,1,0], low=0, mid=0, high=5. The loop swaps 0s to front, 2s to end, 1s stay in middle.Step 2: Final sorted array
After processing, nums becomes [0,0,1,1,2,2].Final Answer:
[0 0 1 1 2 2] -> Option BQuick Check:
Sorted colors = [0 0 1 1 2 2] [OK]
- Not updating mid after swapping 0
- Updating mid after swapping 2 incorrectly
- Confusing order of swaps
nums := []int{2,0,1}
low, mid, high := 0, 0, len(nums)-1
for mid < high {
if nums[mid] == 0 {
nums[low], nums[mid] = nums[mid], nums[low]
low++
mid++
} else if nums[mid] == 2 {
nums[mid], nums[high] = nums[high], nums[mid]
high--
} else {
mid++
}
}
fmt.Println(nums)Solution
Step 1: Check loop condition
The loop uses 'mid < high' but it should be 'mid <= high' to process all elements including when mid equals high.Step 2: Effect of wrong condition
With 'mid < high', the last element may not be processed, causing incorrect sorting.Final Answer:
Loop condition should be mid <= high, not mid < high -> Option CQuick Check:
Loop must cover all elements [OK]
- Using mid < high misses last element
- Incorrect pointer initialization
- Swapping logic errors
nums containing only 0s, 1s, and 2s, how would you modify the Dutch Flag algorithm to count the number of swaps performed during sorting?Solution
Step 1: Understand swap points
Swaps happen when 0s or 2s are moved by exchanging elements inside the loop.Step 2: Implement swap counter
Introduce a variable initialized to 0 before the loop and increment it each time a swap statement executes.Final Answer:
Add a counter and increment it each time a swap occurs inside the loop -> Option DQuick Check:
Count swaps during execution [OK]
- Counting swaps after sorting by comparing arrays
- Thinking recursion counts swaps automatically
- Assuming swaps cannot be tracked
Ready to prove it?
Pass the test and this pattern moves unknown
