The Dutch National Flag Algorithm: A Detailed Explanation

The Dutch National Flag Algorithm: A Detailed Explanation

The Dutch National Flag Algorithm

The Dutch National Flag Algorithm, proposed by Edsger Dijkstra, is a classic computer science problem-solving approach. It is named after the Dutch flag, which consists of three distinct colored sections: red, white, and blue. The algorithm is primarily used to sort an array containing three distinct types of elements (or values) efficiently, in linear time, with constant space.


Problem Statement

You are given an array containing three types of elements, such as:

  • 0, 1, and 2, or

  • Red, White, and Blue, or any other three distinct values.

The goal is to rearrange the array so that:

  • All elements of the first type come first,

  • All elements of the second type come next,

  • All elements of the third type come last.

For instance:

  • Input: [2, 0, 2, 1, 1, 0]

  • Output: [0, 0, 1, 1, 2, 2]


Key Concepts

The algorithm utilizes three pointers:

  1. Low (L): Marks the boundary for the first type (e.g., 0s).

  2. High (H): Marks the boundary for the third type (e.g., 2s).

  3. Mid (M): Iterates through the array, determining the type of the current element.


Steps of the Algorithm

  1. Initialize Pointers:

    • Set low = 0, mid = 0, and high = n - 1 (where n is the length of the array).
  2. Iterate While mid <= high:

    • Examine the element at mid:

      • If it's the first type (e.g., 0):

        • Swap the element at mid with the element at low.

        • Increment both low and mid.

      • If it's the second type (e.g., 1):

        • Just increment mid.
      • If it's the third type (e.g., 2):

        • Swap the element at mid with the element at high.

        • Decrement high.

  3. Stop When mid > high:

    • At this point, the array is fully sorted.

Code Implementation in Python

Here’s how you can implement the Dutch National Flag Algorithm:

def dutch_national_flag(arr):
    low, mid, high = 0, 0, len(arr) - 1

    while mid <= high:
        if arr[mid] == 0:  # First type
            arr[low], arr[mid] = arr[mid], arr[low]
            low += 1
            mid += 1
        elif arr[mid] == 1:  # Second type
            mid += 1
        else:  # Third type
            arr[mid], arr[high] = arr[high], arr[mid]
            high -= 1
    return arr

# Example usage
array = [2, 0, 2, 1, 1, 0]
sorted_array = dutch_national_flag(array)
print("Sorted Array:", sorted_array)

Example Walkthrough

For the array [2, 0, 2, 1, 1, 0]:

StepLowMidHighArrayAction
1005[2, 0, 2, 1, 1, 0]Swap mid & high
2004[0, 0, 2, 1, 1, 2]Swap mid & low
3114[0, 0, 2, 1, 1, 2]Increment mid
4124[0, 0, 1, 1, 1, 2]Increment mid
5134[0, 0, 1, 1, 1, 2]Sorted!

Complexity Analysis

  • Time Complexity: O(n)O(n), as the algorithm processes each element exactly once.

  • Space Complexity: O(1)O(1), as it uses only a constant amount of extra space.


When to Use the Dutch National Flag Algorithm

  1. Sorting Problems: When sorting an array with a limited range of distinct values.

  2. Color Segregation: Partitioning objects or data into three categories efficiently.

  3. Interview Questions: Frequently asked in coding interviews as a test of problem-solving and optimization skills.


Real-World Analogies

Think of it as organizing a pile of laundry with three types of clothes (e.g., shirts, pants, and socks). The algorithm ensures each type is grouped together in an efficient manner.


Conclusion

The Dutch National Flag Algorithm is an elegant and efficient way to sort an array with three distinct categories. Its combination of simplicity and performance makes it a go-to solution for a wide range of problems in computer science and software engineering.