Sort Colors Using Two Pointer Dutch Flag Algorithm
📖 Scenario: You are organizing colored balls in a line. The balls can be red, white, or blue, represented by numbers 0, 1, and 2 respectively. Your task is to sort them so that all reds come first, then whites, and then blues.
🎯 Goal: Build a program that sorts an array of numbers representing colors (0, 1, 2) using the two-pointer Dutch Flag algorithm.
📋 What You'll Learn
Create an array called colors with the exact values [2, 0, 2, 1, 1, 0].
Create two pointer variables called low and high to track positions.
Use a while loop with a variable current to sort the array in-place.
Print the sorted colors array at the end.
💡 Why This Matters
🌍 Real World
Sorting colored objects quickly is useful in games, graphics, and organizing items by categories.
💼 Career
Understanding two-pointer techniques and in-place sorting is important for coding interviews and efficient algorithm design.
Progress0 / 4 steps
1
Create the initial colors array
Create an array called colors with these exact values: [2, 0, 2, 1, 1, 0].
DSA Javascript
Hint
Use const colors = [2, 0, 2, 1, 1, 0]; to create the array.
2
Set up pointers for sorting
Create variables low set to 0, high set to colors.length - 1, and current set to 0.
DSA Javascript
Hint
Initialize low, high, and current as described.
3
Implement the two-pointer sorting logic
Use a while loop with the condition current <= high. Inside the loop, use if statements to check colors[current]. If it is 0, swap with colors[low], increment low and current. If it is 2, swap with colors[high] and decrement high. If it is 1, just increment current.
DSA Javascript
Hint
Use a while loop and swap elements using array destructuring.
4
Print the sorted colors array
Write console.log(colors) to print the sorted colors array.
DSA Javascript
Hint
Use console.log(colors) to display the sorted array.
Practice
(1/5)
1. What is the main goal of the Sort Colors Two Pointer Dutch Flag algorithm?
easy
A. To find the maximum value in an array
B. To sort any array of integers in ascending order
C. To reverse the elements of an array
D. To sort an array containing only 0s, 1s, and 2s in a single pass
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 sort these values 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 D
Quick Check:
Sort Colors = Sort 0,1,2 in one pass [OK]
Hint: Remember: Dutch Flag sorts 0,1,2 in one pass [OK]
Common Mistakes:
Thinking it sorts any integer array
Confusing it with general sorting algorithms
Assuming it reverses the array
2. Which of the following is the correct initialization for the two pointers in the Dutch Flag algorithm in JavaScript?
easy
A. let low = 0, mid = 0, high = nums.length - 1;
B. let low = 0, mid = nums.length - 1, high = 0;
C. let low = nums.length - 1, mid = 0, high = 0;
D. let low = nums.length - 1, mid = nums.length - 1, high = 0;
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 to roles
Correct initialization is let low = 0, mid = 0, high = nums.length - 1;.
Final Answer:
let low = 0, mid = 0, high = nums.length - 1; -> Option A
Quick Check:
Pointers start low=0, mid=0, high=end [OK]
Hint: Start low and mid at 0, high at array end [OK]
Common Mistakes:
Swapping high and mid initialization
Starting pointers at wrong indices
Using length instead of length - 1 for high
3. What will be the output array after running the Dutch Flag algorithm on nums = [2, 0, 2, 1, 1, 0]?
medium
A. [0, 0, 1, 1, 2, 2]
B. [2, 2, 1, 1, 0, 0]
C. [0, 1, 0, 1, 2, 2]
D. [1, 0, 2, 0, 1, 2]
Solution
Step 1: Apply Dutch Flag sorting logic
Sort 0s to front, 1s in middle, 2s at end in one pass.
Step 2: Result after sorting
The sorted array is [0, 0, 1, 1, 2, 2].
Final Answer:
[0, 0, 1, 1, 2, 2] -> Option A
Quick Check:
Sorted colors = 0s, then 1s, then 2s [OK]
Hint: Sort 0s front, 1s middle, 2s end in one pass [OK]
Common Mistakes:
Not sorting all 0s to front
Mixing order of 1s and 2s
Returning original unsorted array
4. Identify the bug in this snippet of the Dutch Flag algorithm:
let low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] === 0) {
[nums[low], nums[mid]] = [nums[mid], nums[low]];
low++;
} else if (nums[mid] === 2) {
[nums[mid], nums[high]] = [nums[high], nums[mid]];
high--;
} else {
mid++;
}
}
medium
A. Incorrect comparison operator in while loop
B. Missing increment of mid after swapping 0s
C. Swapping 2s with low instead of high
D. No bug, code is correct
Solution
Step 1: Analyze pointer increments after swaps
When swapping 0s, mid pointer must also move forward to avoid infinite loop.
Step 2: Identify missing mid++ after swapping 0s
The code increments low but forgets to increment mid after swapping 0s.
Final Answer:
Missing increment of mid after swapping 0s -> Option B
Quick Check:
mid++ missing after 0 swap causes infinite loop [OK]
Hint: Increment mid after swapping 0s to avoid infinite loop [OK]
Common Mistakes:
Forgetting mid++ after swapping 0s
Swapping 2s with wrong pointer
Incorrect loop condition
5. Given an array nums with values 0, 1, and 2, how would you modify the Dutch Flag algorithm to count how many swaps are performed during sorting?
hard
A. Use a separate array to track swaps
B. Count the number of 0s, 1s, and 2s before sorting
C. Add a counter variable and increment it each time a swap occurs
D. Increment a counter only when mid pointer moves
Solution
Step 1: Understand swap operations in algorithm
Swaps happen when 0 or 2 is encountered and elements are exchanged.
Step 2: Track swaps with a counter
Introduce a variable initialized to zero and increment it every time a swap line executes.
Final Answer:
Add a counter variable and increment it each time a swap occurs -> Option C
Quick Check:
Count swaps by incrementing counter on each swap [OK]
Hint: Increment counter inside swap blocks to count swaps [OK]
Common Mistakes:
Counting pointer moves instead of swaps
Counting elements instead of swaps
Using extra arrays unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.