Fetching latest headlines…
Sort 0s, 1s and 2s (Dutch National Flag Problem)
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

Sort 0s, 1s and 2s (Dutch National Flag Problem)

1 views0 likes0 comments
Originally published byDev.to

Sort 0s, 1s and 2s (Dutch National Flag Problem)
Problem Statement
Given an array arr[] containing only 0s, 1s, and 2s, sort the array in ascending order.
Constraint:
You cannot use built-in sort functions.

Examples
Input: arr = [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]

Input: arr = [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]
________________________________________Objective
β€’ Sort array without using sort()
β€’ Use efficient algorithm (one pass preferred)
β€’ Maintain constant extra space

Approach 1: Counting Method
Idea
β€’ Count number of 0s, 1s, and 2s
β€’ Overwrite the array accordingly

Python Code
arr = [0, 1, 2, 0, 1, 2]

count0 = arr.count(0)
count1 = arr.count(1)
count2 = arr.count(2)

arr = [0]*count0 + [1]*count1 + [2]*count2

print(arr)

Complexity
β€’ Time: O(n)
β€’ Space: O(1) (ignoring output array)

Approach 2: Dutch National Flag Algorithm (Best Solution)
Idea
Use three pointers:
β€’ low β†’ position for 0
β€’ mid β†’ current element
β€’ high β†’ position for 2

Working
β€’ If element is 0 β†’ swap with low, move both pointers
β€’ If element is 1 β†’ move mid
β€’ If element is 2 β†’ swap with high, move high

Python Code
arr = [0, 1, 2, 0, 1, 2]

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], arr[high] = arr[high], arr[mid]
    high -= 1

print(arr)

Step-by-Step Idea
Initial:
[0, 1, 2, 0, 1, 2]
After processing:
[0, 0, 1, 1, 2, 2]

Complexity
β€’ Time: O(n) (single pass)
β€’ Space: O(1)

Comparison
Method Time Complexity Space Passes
Counting O(n) O(1) 2
Dutch Flag O(n) O(1) 1 βœ…

Edge Cases
β€’ All elements same β†’ [0,0,0]
β€’ Already sorted array
β€’ Reverse sorted array

Final Thoughts
β€’ Best approach is Dutch National Flag Algorithm
β€’ Very important for interviews
β€’ Demonstrates:
o Pointer manipulation
o In-place sorting
o Optimization thinking

Comments (0)

Sign in to join the discussion

Be the first to comment!