Bird
Raised Fist0
DSA Javascriptprogramming~15 mins

Dutch National Flag Three Way Partition in DSA Javascript - Deep Dive

Choose your learning style10 modes available
Overview - Dutch National Flag Three Way Partition
What is it?
The Dutch National Flag problem is about sorting an array with three different types of elements into three groups. It rearranges the array so that all elements of the first type come first, then all elements of the second type, and finally all elements of the third type. This is done in one pass without extra space. It is named after the three colors of the Dutch flag: red, white, and blue.
Why it matters
This problem helps solve many real-world sorting tasks where you need to group items quickly and efficiently. Without this method, sorting three groups would take more time or extra memory. It shows how to organize data smartly in one go, which is important for fast and memory-friendly programs.
Where it fits
Before learning this, you should understand basic arrays and simple sorting methods like swapping elements. After this, you can learn more complex sorting algorithms and partitioning techniques used in quicksort and other advanced algorithms.
Mental Model
Core Idea
Divide the array into three parts by moving pointers inward, swapping elements to group them by type in one pass.
Think of it like...
Imagine sorting colored balls into three boxes: red balls go to the left box, white balls in the middle box, and blue balls to the right box. You pick balls one by one and place them in the correct box without mixing them up.
Start: [unknown | middle | unknown]
Indexes: 0       i       j       n-1

Process:
 ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
 │ less than p │ equal to p  │ greater than p│
 ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Pointers:
 - low: boundary for first group
 - mid: current element
 - high: boundary for last group

Loop:
 - If arr[mid] < pivot: swap arr[low] and arr[mid], low++, mid++
 - If arr[mid] == pivot: mid++
 - If arr[mid] > pivot: swap arr[mid] and arr[high], high--
Build-Up - 7 Steps
1
FoundationUnderstanding the Problem Setup
šŸ¤”
Concept: Introduce the problem of sorting an array with three distinct values into separate groups.
Imagine you have an array with only three types of elements, for example, 0, 1, and 2. Your goal is to rearrange the array so that all 0s come first, then all 1s, and finally all 2s. The challenge is to do this efficiently without using extra space or sorting the array multiple times.
Result
You understand the problem: grouping three types of elements in order.
Knowing the problem clearly helps you focus on finding a method that sorts in one pass and uses no extra memory.
2
FoundationBasic Array Swapping Technique
šŸ¤”
Concept: Learn how to swap two elements in an array to change their positions.
Swapping means exchanging the values of two positions in an array. For example, if arr = [0, 2, 1], swapping arr[1] and arr[2] changes it to [0, 1, 2]. This is the basic operation used to reorder elements.
Result
You can swap any two elements in an array to rearrange it.
Mastering swapping is essential because the Dutch National Flag algorithm relies on swapping to group elements correctly.
3
IntermediateIntroducing Three Pointers
šŸ¤”Before reading on: do you think one pointer is enough to sort three groups, or do we need more? Commit to your answer.
Concept: Use three pointers to track boundaries of the three groups during sorting.
We use three pointers: low, mid, and high. Low marks the end of the first group (e.g., 0s), mid scans the array, and high marks the start of the last group (e.g., 2s). We move mid through the array, swapping elements to their correct group by adjusting low and high.
Result
You understand how three pointers help divide the array into three parts dynamically.
Using three pointers lets us sort the array in one pass by keeping track of boundaries for each group.
4
IntermediateStep-by-Step Partitioning Logic
šŸ¤”Before reading on: when mid points to a 2, should we move mid forward or swap with high? Commit to your answer.
Concept: Decide actions based on the current element at mid to maintain group order.
If arr[mid] is less than pivot (e.g., 0), swap with arr[low], then increment low and mid. If arr[mid] equals pivot (e.g., 1), just move mid forward. If arr[mid] is greater than pivot (e.g., 2), swap with arr[high] and decrement high, but do not move mid forward yet because the swapped element needs checking.
Result
You can correctly move elements to their groups while scanning the array once.
Knowing when to move pointers and when to swap prevents missing or misplacing elements during sorting.
5
IntermediateImplementing the Algorithm in JavaScript
šŸ¤”Before reading on: do you think this algorithm requires extra memory or can it sort in place? Commit to your answer.
Concept: Write the full JavaScript function to perform the Dutch National Flag partition.
function dutchNationalFlag(arr, pivot) { let low = 0, mid = 0, high = arr.length - 1; while (mid <= high) { if (arr[mid] < pivot) { [arr[low], arr[mid]] = [arr[mid], arr[low]]; low++; mid++; } else if (arr[mid] === pivot) { mid++; } else { [arr[mid], arr[high]] = [arr[high], arr[mid]]; high--; } } } // Example usage: const arr = [2, 0, 1, 2, 1, 0]; dutchNationalFlag(arr, 1); console.log(arr);
Result
Output: [0, 0, 1, 1, 2, 2]
Implementing the algorithm solidifies understanding and shows how to sort three groups efficiently in place.
6
AdvancedHandling Arbitrary Three Values
šŸ¤”Before reading on: can this algorithm work if the three values are not 0, 1, and 2 but any three distinct values? Commit to your answer.
Concept: Generalize the algorithm to work with any three distinct values by choosing a pivot and comparing accordingly.
The algorithm works by choosing one value as the pivot (middle group). Elements less than pivot go to the left, greater go to the right. For example, if the array has ['apple', 'banana', 'cherry'], pick 'banana' as pivot. Compare elements lexicographically or by custom rules to decide swaps.
Result
You can sort arrays with any three distinct values, not just numbers.
Understanding the pivot concept allows applying the algorithm beyond simple numeric cases.
7
ExpertOptimizing for Stability and Variations
šŸ¤”Before reading on: do you think the Dutch National Flag algorithm is stable (preserves order of equal elements)? Commit to your answer.
Concept: Explore the algorithm's stability and how to modify it for stable sorting or related partitioning tasks.
The classic Dutch National Flag algorithm is not stable because it swaps elements freely. To make it stable, you need extra memory or a different approach, like counting elements first or using linked lists. Also, variations exist for more than three groups or for streaming data where you can't access all elements at once.
Result
You know the limits of the algorithm and how to adapt it for special cases.
Recognizing stability and adaptability helps choose the right algorithm for real-world needs.
Under the Hood
The algorithm uses three pointers to partition the array into three sections dynamically. It scans the array once, swapping elements to their correct section by comparing with the pivot. The low pointer marks the boundary of the first group, mid scans elements, and high marks the boundary of the last group. Swapping is done in place, so no extra memory is needed. The mid pointer only advances when the current element is in the middle group or after swapping a smaller element forward. When swapping a larger element backward, mid stays to check the new element.
Why designed this way?
This method was designed to solve the problem of sorting three groups efficiently in one pass and without extra space. Earlier methods required multiple passes or extra arrays, which were slower or used more memory. The three-pointer approach balances simplicity and efficiency, inspired by Edsger Dijkstra's work on the Dutch National Flag problem. It avoids unnecessary comparisons and swaps by carefully moving pointers.
Array: [  ] [  ] [  ] ... [  ]
Indexes: 0    low    mid    high    n-1

Process:
 ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
 │ < pivot     │ == pivot    │ > pivot     │
 ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Pointers move:
 - If arr[mid] < pivot: swap with arr[low], low++, mid++
 - If arr[mid] == pivot: mid++
 - If arr[mid] > pivot: swap with arr[high], high--

Loop ends when mid > high.
Myth Busters - 4 Common Misconceptions
Quick: Does the algorithm require sorting the array multiple times? Commit to yes or no.
Common Belief:The Dutch National Flag algorithm sorts the array by running multiple passes over it.
Tap to reveal reality
Reality:It sorts the array in a single pass by using three pointers and swapping elements in place.
Why it matters:Thinking it needs multiple passes leads to inefficient solutions and misses the algorithm's main advantage.
Quick: Is the algorithm stable, preserving the order of equal elements? Commit to yes or no.
Common Belief:The algorithm keeps the original order of elements with the same value (stable).
Tap to reveal reality
Reality:It is not stable because it swaps elements freely, which can change the order of equal elements.
Why it matters:Assuming stability can cause bugs when order matters, such as sorting records with keys.
Quick: Can this algorithm only sort arrays with values 0, 1, and 2? Commit to yes or no.
Common Belief:The algorithm only works for arrays containing exactly 0, 1, and 2.
Tap to reveal reality
Reality:It works for any three distinct values as long as you choose a pivot and compare correctly.
Why it matters:Limiting the algorithm to specific values restricts its usefulness and understanding.
Quick: Does the algorithm require extra memory to hold temporary arrays? Commit to yes or no.
Common Belief:You need extra arrays or memory to sort the three groups separately.
Tap to reveal reality
Reality:The algorithm sorts in place without extra memory by swapping elements within the original array.
Why it matters:Using extra memory unnecessarily increases space complexity and reduces efficiency.
Expert Zone
1
The order of pointer movements and swaps is critical; swapping with high pointer does not advance mid to ensure the swapped element is checked.
2
Choosing the pivot value carefully affects the algorithm's correctness and generalization to non-numeric data.
3
The algorithm can be adapted for streaming data or linked lists but requires different pointer management.
When NOT to use
Avoid this algorithm when you need a stable sort or when sorting more than three groups; in those cases, use counting sort, radix sort, or comparison-based stable sorts like mergesort.
Production Patterns
Used in quicksort partitioning as a three-way partition to handle duplicates efficiently; also used in color sorting in graphics, categorizing data into three buckets quickly, and in network packet classification.
Connections
Quicksort Three-Way Partitioning
Builds-on
Understanding the Dutch National Flag algorithm helps grasp how quicksort handles duplicates by partitioning into less than, equal to, and greater than pivot groups.
Counting Sort
Alternative approach
Counting sort also groups elements by value but uses extra memory; comparing it with Dutch National Flag highlights trade-offs between space and time.
Traffic Light Control Systems
Analogous pattern
Like the Dutch flag groups colors, traffic lights manage three states (red, yellow, green) in order, showing how partitioning concepts appear in real-world control systems.
Common Pitfalls
#1Advancing mid pointer after swapping with high pointer.
Wrong approach:if (arr[mid] > pivot) { [arr[mid], arr[high]] = [arr[high], arr[mid]]; high--; mid++; // wrong: mid should not advance here }
Correct approach:if (arr[mid] > pivot) { [arr[mid], arr[high]] = [arr[high], arr[mid]]; high--; // mid stays to check swapped element }
Root cause:Misunderstanding that the swapped element from the end might be less or equal to pivot and needs checking.
#2Using the wrong pivot value or not defining it clearly.
Wrong approach:const pivot = 3; // pivot not in array or not one of the three values // leads to incorrect comparisons and sorting
Correct approach:const pivot = 1; // pivot chosen as the middle value present in array
Root cause:Not choosing a pivot that correctly divides the three groups causes incorrect partitioning.
#3Trying to make the algorithm stable by avoiding swaps.
Wrong approach:// skipping swaps to preserve order if (arr[mid] < pivot) { mid++; } else if (arr[mid] === pivot) { mid++; } else { mid++; }
Correct approach:if (arr[mid] < pivot) { [arr[low], arr[mid]] = [arr[mid], arr[low]]; low++; mid++; } else if (arr[mid] === pivot) { mid++; } else { [arr[mid], arr[high]] = [arr[high], arr[mid]]; high--; }
Root cause:Confusing stability with correctness; avoiding swaps breaks the grouping logic.
Key Takeaways
The Dutch National Flag algorithm efficiently sorts arrays with three distinct values in one pass using three pointers and in-place swaps.
Choosing and comparing with a pivot value divides the array into less than, equal to, and greater than groups dynamically.
The algorithm is not stable, so it may change the order of equal elements, which matters in some applications.
Understanding pointer movement and swap conditions is crucial to avoid common mistakes and ensure correctness.
This algorithm forms the basis for advanced sorting techniques like quicksort's three-way partitioning and can be generalized beyond numeric values.

Practice

(1/5)
1. What is the main goal of the Dutch National Flag Three Way Partition algorithm?
easy
A. To find the maximum element in an array
B. To sort an array in ascending order using quicksort
C. To reverse the elements of an array
D. To rearrange an array so that all elements less than a pivot come first, then equal elements, then greater elements

Solution

  1. Step 1: Understand the partition goal

    The algorithm divides the array into three parts: less than pivot, equal to pivot, and greater than pivot.
  2. Step 2: Identify the rearrangement

    It rearranges elements so that all smaller come first, then equal, then larger, without full sorting.
  3. Final Answer:

    To rearrange an array so that all elements less than a pivot come first, then equal elements, then greater elements -> Option D
  4. Quick Check:

    Partitioning = Rearranging by pivot [OK]
Hint: Remember: three parts - less, equal, greater [OK]
Common Mistakes:
  • Confusing partition with full sorting
  • Thinking it only finds max or min
  • Assuming it reverses the array
2. Which of the following is the correct way to initialize pointers for the Dutch National Flag algorithm in JavaScript?
easy
A. let low = 0, mid = 0, high = arr.length - 1;
B. let low = arr.length - 1, mid = 0, high = 0;
C. let low = 0, mid = arr.length - 1, high = 0;
D. let low = 0, mid = 1, high = arr.length;

Solution

  1. Step 1: Identify pointer roles

    Low and mid start at 0, high at last index to cover full array.
  2. Step 2: Match initialization to algorithm

    Correct initialization is low=0, mid=0, high=arr.length-1 to scan and partition properly.
  3. Final Answer:

    let low = 0, mid = 0, high = arr.length - 1; -> Option A
  4. Quick Check:

    Pointers start at array ends and middle [OK]
Hint: Start low and mid at 0, high at last index [OK]
Common Mistakes:
  • Setting high to 0 instead of last index
  • Starting mid at wrong position
  • Using array length instead of length - 1
3. What will be the output of the following code snippet?
function dutchFlag(arr, pivot) {
  let low = 0, mid = 0, high = arr.length - 1;
  while (mid <= high) {
    if (arr[mid] < pivot) {
      [arr[low], arr[mid]] = [arr[mid], arr[low]];
      low++; mid++;
    } else if (arr[mid] === pivot) {
      mid++;
    } else {
      [arr[mid], arr[high]] = [arr[high], arr[mid]];
      high--;
    }
  }
  return arr;
}

console.log(dutchFlag([2, 5, 1, 2, 3, 2, 4], 2));
medium
A. [1, 2, 2, 2, 5, 3, 4]
B. [2, 2, 2, 1, 3, 4, 5]
C. [1, 2, 2, 2, 3, 4, 5]
D. [1, 2, 2, 2, 4, 3, 5]

Solution

  1. Step 1: Trace swaps for elements less than pivot

    Elements less than 2 (which is 1) move to front; 1 swaps to index 0.
  2. Step 2: Place all 2s in middle and greater elements at end

    All 2s stay in middle; 3,4,5 move to the right side in any order preserving partition.
  3. Final Answer:

    [1, 2, 2, 2, 3, 4, 5] -> Option C
  4. Quick Check:

    Partitioned array with less, equal, greater [OK]
Hint: Swap less than pivot left, greater right [OK]
Common Mistakes:
  • Not swapping correctly when element equals pivot
  • Mixing order of greater elements
  • Forgetting to increment mid after swap with low
4. Identify the bug in this Dutch National Flag partition code:
function partition(arr, pivot) {
  let low = 0, mid = 0, high = arr.length - 1;
  while (mid < high) {
    if (arr[mid] < pivot) {
      [arr[low], arr[mid]] = [arr[mid], arr[low]];
      low++;
      mid++;
    } else if (arr[mid] === pivot) {
      mid++;
    } else {
      [arr[mid], arr[high]] = [arr[high], arr[mid]];
      high--;
    }
  }
  return arr;
}
medium
A. The pointers low and mid are initialized incorrectly
B. The while loop condition should be mid <= high, not mid < high
C. The swap operation is missing for elements equal to pivot
D. The high pointer should be incremented, not decremented

Solution

  1. Step 1: Check loop condition correctness

    The loop must run while mid is less than or equal to high to process all elements.
  2. Step 2: Identify impact of incorrect condition

    Using mid < high skips processing when mid equals high, missing last element check.
  3. Final Answer:

    The while loop condition should be mid <= high, not mid < high -> Option B
  4. Quick Check:

    Loop must cover all elements [OK]
Hint: Use mid <= high to cover all elements [OK]
Common Mistakes:
  • Using mid < high causes last element to be skipped
  • Incorrect pointer initialization
  • Misunderstanding swap necessity for equal elements
5. Given an array [4, 9, 4, 7, 4, 8, 7] and pivot value 7, what will be the final array after applying the Dutch National Flag partition algorithm?
hard
A. [4, 4, 4, 7, 7, 8, 9]
B. [4, 4, 4, 7, 8, 7, 9]
C. [4, 4, 4, 7, 8, 9, 7]
D. [7, 7, 4, 4, 4, 8, 9]

Solution

  1. Step 1: Partition elements less than pivot (7)

    All 4s move to the front: [4, 4, 4, ...]
  2. Step 2: Place all 7s in the middle and greater elements at the end

    7s stay in the middle; 8 and 9 move to the right side in sorted order.
  3. Final Answer:

    [4, 4, 4, 7, 7, 8, 9] -> Option A
  4. Quick Check:

    Less, equal, greater partitioned correctly [OK]
Hint: Group less, equal, greater around pivot [OK]
Common Mistakes:
  • Mixing order of greater elements
  • Placing pivot elements incorrectly
  • Not moving all less elements to front
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard