Explain the Dutch National Flag algorithm.
Skip to solutionKEEP THE
mediumDSA
How do you sort an array of 0s, 1s, and 2s?
826 views
01
Understand the problem
arrayssortingdutch-flag
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Dutch National Flag: keep low, mid, high pointers. Sweep mid: swap 0s to the front (low), leave 1s, swap 2s to the back (high). One pass partitions all three values in O(n) time, O(1) space.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Dutch National Flag
Run Playgrounddef sort_colors(nums):
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1; mid += 1
elif nums[mid] == 1:
mid += 1
else: # == 2
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1 # do NOT advance mid
return nums
# --- demo ---
print(sort_colors([2, 0, 2, 1, 1, 0])) # [0, 0, 1, 1, 2, 2]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 45 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.