Back to articles
How I understood sorting 0s,1s and 2s

How I understood sorting 0s,1s and 2s

via Dev.to PythonAbinaya Dhanraj

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 mi

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles