QA
Intermediate LevelData Structures & Algorithms

How does the Dutch National Flag algorithm sort an array of 0s, 1s, and 2s in O(N)?

ā“ Interview Prompt: Solve Sort Colors (0s, 1s, 2s) using the Dutch National Flag algorithm with O(N) time and O(1) space.

Dutch National Flag (Dijkstra) partitions an array into three sections in a single pass using three pointers.

Pointers:

•
lo: boundary of 0s (left section ends here).
•
mid: current element being processed.
•
hi: boundary of 2s (right section starts here).

Invariants:

•
arr[0..lo-1] = all 0s.
•
arr[lo..mid-1] = all 1s.
•
arr[mid..hi] = unknown.
•
arr[hi+1..n-1] = all 2s.

Code Implementation Example

typescript
function sortColors(nums: number[]): void {
  let lo = 0, mid = 0, hi = nums.length - 1;

  while (mid <= hi) {
    if (nums[mid] === 0) {
      [nums[lo], nums[mid]] = [nums[mid], nums[lo]];
      lo++; mid++;
    } else if (nums[mid] === 1) {
      mid++; // 1 is in correct region
    } else { // nums[mid] === 2
      [nums[mid], nums[hi]] = [nums[hi], nums[mid]];
      hi--; // don't advance mid — swapped element unknown!
    }
  }
}

const arr = [2, 0, 2, 1, 1, 0];
sortColors(arr);
console.log(arr); // [0, 0, 1, 1, 2, 2]
šŸ’”Dutch National Flag 3-way partition — O(N) single-pass, O(1) space.
šŸŽÆ Interview Key Takeaway

Dutch National Flag is a 3-way partition running in O(N)/O(1). Key: when swapping with hi, don't advance mid — the swapped element is unprocessed.

#DSA#Dutch National Flag#Sorting#Two Pointers#Intermediate
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?