FlareStart
HomeNewsHow ToSources
FlareStart

Where developers start their day. All the tech news & tutorials that matter, in one place.

Quick Links

  • Home
  • News
  • Tutorials
  • Sources
  • Privacy Policy

Connect

© 2026 FlareStart. All rights reserved.

Back to articles
Sorting 0s, 1s, and 2s Using the Counting Method in Python
How-ToProgramming Languages

Sorting 0s, 1s, and 2s Using the Counting Method in Python

via Dev.to PythonSri Mahalakshmi3h ago

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

Read Full Article
0 views

Related Articles

How to Back Up Your Android Phone (2026)
How-To

How to Back Up Your Android Phone (2026)

Wired • 51m ago

Mining the deep ocean
How-To

Mining the deep ocean

Ars Technica • 1h ago

CA 08 - Sort 0s, 1s, and 2s
How-To

CA 08 - Sort 0s, 1s, and 2s

Dev.to • 2h ago

PDF to LaTeX Conversion: Why It's Hard and What Actually Works
How-To

PDF to LaTeX Conversion: Why It's Hard and What Actually Works

Dev.to Tutorial • 2h ago

The Art of Motivation and Inspiration ✨
How-To

The Art of Motivation and Inspiration ✨

Medium Programming • 4h ago

Discover More Articles