"Sorting 0s, 1s, and 2s using Counting Sort"

📌 Day 22/100 – Sort Colors (LeetCode 75) 🔹 Problem: Given an array containing 0s, 1s, and 2s (representing red, white, and blue), sort them in-place so that all same colors stay together in the order: 0 → 1 → 2. No built-in sorting allowed. 🔹 Approach Used: Counting Sort Count occurrences of 0, 1, and 2. Overwrite the array based on those counts. Done in single pass + rewrite, no extra sorting logic needed. 🔹 Time & Space Complexity: ⏳ Time: O(n) — one pass to count, one pass to rewrite 🧠 Space: O(1) — constant extra space 🔹 Key Learnings: ✅ Problems become simpler when we leverage constraints (only 3 values here) ✅ Counting sort is perfect when input range is small & fixed ✅ Always look for in-place optimizations before thinking of extra space #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories