The Dutch National Flag algorithm was proposed by Edsger Dijkstra to sort an array with three distinct values. The most common example is sorting an array containing only 0, 1 and 2. The algorithm efficiently sorts the array in a single pass.
Given an array of n elements where each element is either 0, 1 or 2, the goal is to sort the array such that all 0s come first, followed by 1s and then all 2s.
The Dutch National Flag problem divides the array into three partitions:
0s1s2sWe use three pointers: low, mid and high. low tracks the boundary where 0s should end. mid traverses through the array. high tracks the boundary where 2s should begin.
The algorithm processes the array in one pass:
0: swap it with the element at low, then increment both low and mid1: leave it in place and just move the mid pointer.2: swap it with the element at high and decrement highdef dutch_national_flag(arr):
low, mid = 0, 0
high = len(arr) - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arrThe time complexity of Dutch National Flag algorithm is O(n)
The space complexity of Dutch National Flag algorithm is O(1)