
Sorting 0s, 1s, and 2s Using the Counting Method in Python
Problem Explanation You are given an array that contains only 0s, 1s, and 2s . Your task is to sort the array in ascending order without using any built-in sort function . Example: Input: arr = [0, 1, 2, 0, 1, 2] Output: [0, 0, 1, 1, 2, 2] Idea Behind the Solution Instead of comparing and swapping elements, we do something smarter: Count how many 0s, 1s, and 2s are present Rewrite the array using those counts This avoids unnecessary operations and keeps the logic simple. Python Code with Explanation class Solution : def sort012 ( self , arr ): count0 = 0 We create a variable count0 to store how many times 0 appears in the array. count1 = 0 This variable stores how many times 1 appears. count2 = 0 This variable stores how many times 2 appears. for num in arr : We loop through each element in the array one by one. if num == 0 : count0 += 1 If the element is 0, we increase the count of 0s. elif num == 1 : count1 += 1 If the element is 1, we increase the count of 1s. else : count2 += 1 If
Continue reading on Dev.to Python
Opens in a new tab




