Sort Colors Two Pointer Dutch Flag in DSA Java - 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.
public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
int temp = nums[low];
nums[low] = nums[mid];
nums[mid] = temp;
low++; mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
int temp = nums[mid];
nums[mid] = nums[high];
nums[high] = temp;
high--;
}
}
}
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 that moves the mid pointer through the array.
- How many times: Each element is visited at most once by mid, so up to n times where n is array length.
As the array size grows, the number of steps grows roughly the same as the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps increase linearly with input size.
Time Complexity: O(n)
This means the time to sort grows directly in proportion to the number of elements.
[X] Wrong: "Because there are nested if-else checks, the time complexity must be quadratic O(n²)."
[OK] Correct: The loop runs only once through the array, and each element is handled in constant time, so the overall time is linear, not quadratic.
Knowing this linear time sorting method shows you can handle problems efficiently by using pointers smartly, a skill valued in many coding challenges.
"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 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 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 roles
Low and mid start at the beginning (index 0), high starts at the end (last index).Step 2: Match initialization with roles
int low = 0, mid = 0, high = arr.length - 1; correctly sets low and mid to 0, and high to last index (arr.length - 1).Final Answer:
int low = 0, mid = 0, high = arr.length - 1; -> Option DQuick Check:
Pointers start low=0, mid=0, high=end [OK]
- Setting pointers all to zero
- Starting high pointer at 0 instead of end
- Confusing mid and high initial positions
int[] arr = {2, 0, 2, 1, 1, 0};?Solution
Step 1: Apply Dutch Flag sorting logic
Start with low=0, mid=0, high=5. Swap 2 with 0 at low, move pointers accordingly to group 0s, then 1s, then 2s.Step 2: Final sorted array
After sorting, the array becomes [0, 0, 1, 1, 2, 2].Final Answer:
[0, 0, 1, 1, 2, 2] -> Option BQuick Check:
Sorted colors = 0s, then 1s, then 2s [OK]
- Not swapping correctly
- Mixing order of 1s and 2s
- Assuming original order stays same
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
if (arr[mid] == 0) {
swap(arr, low, mid);
low++;
} else if (arr[mid] == 1) {
mid++;
} else {
swap(arr, mid, high);
high--;
}
}Solution
Step 1: Analyze pointer increments after swaps
When swapping 0, mid pointer must also increment to avoid infinite loop.Step 2: Identify missing mid++ after swapping 0
Code increments low but forgets to increment mid after swapping 0, causing repeated processing of same element.Final Answer:
Missing increment of mid pointer after swapping 0 -> Option CQuick Check:
mid++ needed after swapping 0 [OK]
- Forgetting to increment mid after swap
- Changing while loop condition incorrectly
- Swapping wrong indices
int[] arr = {1, 2, 0, 2, 1, 0, 0, 2, 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,2,1,0,0,2,1]. Swaps occur when 0 or 2 are moved. Counting swaps:
- Swap 1: mid=1 (2) with high=8
- Swap 2: mid=2 (0) with low=0
- Swap 3: mid=3 (2) with high=7
- Swap 4: mid=3 (2) with high=6
- Swap 5: mid=3 (0) with low=1
- Swap 6: mid=5 (0) with low=2Step 2: Total swaps counted
Total swaps performed are 6.Final Answer:
6 -> Option AQuick Check:
Count swaps carefully during pointer moves [OK]
- Counting swaps only for 0s
- Ignoring swaps when swapping with same value
- Miscounting pointer moves as swaps
Ready to prove it?
Pass the test and this pattern moves unknown
