Back to 20 Concepts
two-pointerAdvanced

Dutch National Flag: In-Place 3-Way Partitioning

Dijkstra's Dutch National Flag algorithm partitions an array into three buckets (e.g. 0s, 1s, 2s or < pivot, == pivot, > pivot) in-place in a single pass with 3 pointers (low, mid, high).

Intuitive Mental Model

The Sorting Hopper: Items drop into the middle (mid). Red balls (0) are tossed left (low++), blue balls (2) are tossed right (high--), and white balls (1) stay in place (mid++).

C / TypeScript ImplementationHardware & Algorithmic Standard
function sortColors(nums: number[]): void {
  let low = 0;
  let mid = 0;
  let high = nums.length - 1;

  while (mid <= high) {
    if (nums[mid] === 0) {
      [nums[low], nums[mid]] = [nums[mid], nums[low]];
      low++;
      mid++;
    } else if (nums[mid] === 1) {
      mid++;
    } else {
      [nums[mid], nums[high]] = [nums[high], nums[mid]];
      high--; // mid pointer stays to evaluate swapped item
    }
  }
}

Key Architectural Takeaways

  • Dual-Pivot QuickSort: Fundamental partitioning subroutine in high-performance sorting engines.
  • O(N) Time, O(1) Space: Guarantees every element is examined at most twice.
Common Coding Mistake

Incrementing the mid pointer after swapping with high, missing un-evaluated elements.

Optimal Solution

Only increment mid when swapping with low or when nums[mid] == 1.