π΅ 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 Stateme...

Source: DEV Community
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] 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] π§ 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: Initialize: low = 0 mid = 0 high = n - 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 ```pyth