DEV Community

Navin S
Navin S

Posted on

๐Ÿ”ต Sort 0s, 1s and 2s (Dutch National Flag Algorithm)

Sorting an array containing only 0s, 1s, and 2s is a classic problem in Data Structures.
It is commonly solved using the Dutch National Flag Algorithm, which is highly efficient.


๐Ÿ“Œ Problem Statement

Given an array arr[] containing only 0, 1, and 2, sort the array in ascending order without using built-in sort.


๐Ÿ” Examples

Example 1:

Input:  [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input:  [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Concept

We divide the array into three regions:

  • Left โ†’ all 0s
  • Middle โ†’ all 1s
  • Right โ†’ all 2s

We use three pointers:

  • low โ†’ position for next 0
  • mid โ†’ current element
  • high โ†’ position for next 2

๐Ÿ”„ Approach: One-Pass (Optimal Solution)

Step-by-Step:

  1. Initialize:
  • low = 0
  • mid = 0
  • high = n - 1
  1. Traverse while mid <= high:
  • If arr[mid] == 0:

    • Swap arr[low] and arr[mid]
    • low++, mid++
  • If arr[mid] == 1:

    • Move mid++
  • If arr[mid] == 2:

    • Swap arr[mid] and arr[high]
    • high-- (do NOT increment mid here)

๐Ÿ’ป Python Code

```python id="c1i8rm"
def sort_012(arr):
low = 0
mid = 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] == 2
        arr[mid], arr[high] = arr[high], arr[mid]
        high -= 1

return arr
Enter fullscreen mode Exit fullscreen mode

Example

print(sort_012([0, 1, 2, 0, 1, 2]))




---

## ๐Ÿงพ Dry Run (Step-by-Step)

For:



```id="m3z2fg"
arr = [0, 1, 2, 0, 1, 2]
Enter fullscreen mode Exit fullscreen mode
Step low mid high Array
1 0 0 5 [0, 1, 2, 0, 1, 2]
2 1 1 5 [0, 1, 2, 0, 1, 2]
3 1 1 4 [0, 1, 1, 0, 1, 2]
4 1 2 4 [0, 1, 1, 0, 1, 2]
5 2 3 4 [0, 0, 1, 1, 1, 2]

Final โ†’ [0, 0, 1, 1, 2, 2]


โšก Time and Space Complexity

  • Time Complexity: O(n) (single traversal)
  • Space Complexity: O(1) (in-place)

๐Ÿ” Alternative Approach (Counting Method)

```python id="6qz4ki"
def sort_012(arr):
count0 = arr.count(0)
count1 = arr.count(1)
count2 = arr.count(2)

i = 0
for _ in range(count0):
    arr[i] = 0
    i += 1
for _ in range(count1):
    arr[i] = 1
    i += 1
for _ in range(count2):
    arr[i] = 2
    i += 1

return arr
Enter fullscreen mode Exit fullscreen mode



---

## ๐Ÿงฉ Where Is This Used?

* Partitioning problems
* QuickSort optimizations
* Interview questions

---

## ๐Ÿ Conclusion

The **Dutch National Flag Algorithm** is the best solution for this problem because it:

* Works in **one pass**
* Uses **constant space**
* Is highly efficient

Enter fullscreen mode Exit fullscreen mode

Top comments (0)