How I Understood Sorting 0s, 1s, and 2s (Dutch National Flag Problem)
When I first saw this problem, I thought it would be tricky because it asks to sort in-place without extra space.
But after working through it, I realized the key is simple: three pointers and careful swaps.
Problem
We are given an array containing only 0s, 1s, and 2s.
Example:
Python
arr = [0, 2, 1, 2, 0, 1, 0]
Expected output:
Python
[0, 0, 0, 1, 1, 2, 2]
The goal is to sort the array in a single pass without using extra space.
** What I Noticed**
The array has only three distinct elements.
So instead of using a generic sort, I focused on:
0s to the front
1s in the middle
2s at the end
That’s all we need. No fancy algorithms required.
*What Helped Me*
Using three pointers made everything clear:
low – boundary for 0s
mid – current element being checked
high – boundary for 2s
With this setup, we can swap elements in-place while iterating just once.
Approach
Initialize low = 0, mid = 0, high = len(arr) - 1
While mid <= high:
If arr[mid] == 0: swap with arr[low], move low and mid forward
If arr[mid] == 1: just move mid forward
If arr[mid] == 2: swap with arr[high], move high backward (do not move mid)
Repeat until all elements are in the correct position
Code (Python)
Python
class Solution:
def sort012(self, 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[high], arr[mid] = arr[mid], arr[high]
high -= 1
return arr
Complexity
Time: O(n) – only one pass through the array
Space: O(1) – sorting in-place
What I Learned
This problem is less about complex logic and more about:
Visualizing the pointers
Swapping elements carefully
Moving step by step
It taught me that small, clear steps beat overthinking.
Final Thought
At first, this problem seemed tricky because of the in-place requirement.
But once I broke it down:
“Where should this 0, 1, or 2 go right now?”
…it became straightforward.
This is a great example of how algorithm thinking beats brute force.
Top comments (0)