Sort Colors Two Pointer Dutch Flag in DSA Rust - Time & Space Complexity
We want to understand how the time needed to sort colors using two pointers changes as the list grows.
How does the number of steps grow when we have more colors to sort?
Analyze the time complexity of the following code snippet.
fn sort_colors(nums: &mut Vec<i32>) {
let (mut low, mut mid, mut high) = (0, 0, nums.len() - 1);
while mid <= high {
if nums[mid] == 0 {
nums.swap(low, mid);
low += 1;
mid += 1;
} else if nums[mid] == 1 {
mid += 1;
} else {
nums.swap(mid, high);
if high == 0 { break; }
high -= 1;
}
}
}
This code sorts an array containing 0s, 1s, and 2s by moving pointers and swapping elements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs through the array with the mid pointer.
- How many times: Each element is visited at most once or twice, but the loop moves forward or backward carefully.
As the list size grows, the number of steps grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 to 20 steps |
| 100 | About 100 to 200 steps |
| 1000 | About 1000 to 2000 steps |
Pattern observation: The steps grow roughly linearly with input size.
Time Complexity: O(n)
This means the time to sort grows directly with the number of elements in the list.
[X] Wrong: "Because there are nested ifs and swaps, the time must be quadratic O(n²)."
[OK] Correct: The loop moves pointers carefully so each element is handled only a few times, not repeatedly nested.
Understanding this linear time sorting method shows you can handle problems efficiently with clever pointer use, a skill valued in many coding challenges.
"What if we changed the input to have more than three colors? 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 sorting goal
The goal is to rearrange the array so that all 0s come first, then all 1s, and finally all 2s, in one pass without extra space.Final Answer:
To sort an array containing only 0s, 1s, and 2s in a single pass -> Option AQuick 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: Identify pointer initialization
In the Dutch Flag algorithm,lowandmidstart at 0, andhighstarts at the last index (len() - 1).Step 2: Check mutability and bounds
All pointers must be mutable to move during sorting, andhighmust belen() - 1to avoid out-of-bounds errors.Final Answer:
let mut low = 0; let mut mid = 0; let mut high = nums.len() - 1; -> Option AQuick Check:
Correct pointer setup = let mut low = 0; let mut mid = 0; let mut high = nums.len() - 1; [OK]
- Setting high to nums.len() causing out-of-bounds
- Not using mutable variables
- Starting pointers at wrong indices
let mut nums = vec![2, 0, 2, 1, 1, 0];
let mut low = 0;
let mut mid = 0;
let mut high = nums.len() - 1;
while mid <= high {
match nums[mid] {
0 => {
nums.swap(low, mid);
low += 1;
mid += 1;
},
1 => {
mid += 1;
},
2 => {
nums.swap(mid, high);
if high == 0 { break; }
high -= 1;
},
_ => {}
}
}
println!("{:?}", nums);Solution
Step 1: Trace initial swaps and pointer moves
Starting with nums = [2,0,2,1,1,0], the algorithm swaps 2 at mid with 0 at high, then moves pointers accordingly.Step 2: Continue until mid passes high
After all swaps and increments, the array becomes sorted as [0, 0, 1, 1, 2, 2].Final Answer:
[0, 0, 1, 1, 2, 2] -> Option CQuick Check:
Sorted 0,1,2 array = [0,0,1,1,2,2] [OK]
- Not updating pointers correctly after swap
- Swapping with wrong indices
- Stopping loop too early
let mut nums = vec![2, 0, 1];
let mut low = 0;
let mut mid = 0;
let mut high = nums.len();
while mid <= high {
match nums[mid] {
0 => {
nums.swap(low, mid);
low += 1;
mid += 1;
},
1 => {
mid += 1;
},
2 => {
nums.swap(mid, high);
high -= 1;
},
_ => {}
}
}Solution
Step 1: Check pointer initialization
high is set to nums.len(), which is one past the last valid index, causing out-of-bounds when accessing nums[high].Step 2: Understand valid index range
Valid indices are 0 to nums.len() - 1, so high should be initialized to nums.len() - 1.Final Answer:
high is initialized to nums.len(), causing out-of-bounds access -> Option DQuick Check:
high must be last index, not length [OK]
- Using length instead of last index for high
- Not incrementing mid after swapping 2
- Ignoring pointer bounds
nums = [1, 2, 0, 1, 2, 0, 1], how many swaps will the Dutch Flag algorithm perform to sort it?Solution
Step 1: Trace swaps during sorting
Initial array: [1, 2, 0, 1, 2, 0, 1]. Swaps occur when 0 or 2 is found at mid.Step 2: Count swaps step-by-step
Swaps: - Swap 0 at index 2 with 1 at low (index 0) -> 1 swap - Swap 2 at index 1 with 1 at high (index 6) -> 1 swap - Swap 0 at index 5 with 1 at low (index 1) -> 1 swap - Swap 2 at index 1 with 1 at high (index 5) -> 1 swap Total swaps = 4.Final Answer:
4 -> Option BQuick Check:
Count swaps for 0 and 2 moves = 4 [OK]
- Counting pointer moves as swaps
- Missing swaps when 2 is swapped
- Assuming swaps equal array length
Ready to prove it?
Pass the test and this pattern moves unknown
