Conquering Sort Colors on LeetCode with Counting Sort

DevLog Day 46 Today I finally conquered a problem that had beaten me before. Redemption days hit different. The problem was Sort Colors on LeetCode, a medium level question where you are given an array containing only 0s, 1s, and 2s representing colors, and you need to sort it in place in a single pass. No built in sort, no multiple iterations. The brute force is straightforward, you could use a built in sort function or classic algorithms like bubble sort or insertion sort, but the single pass constraint rules all of that out. My solution used counting sort. Since we only ever have three possible values, I used a fixed size array to count the frequency of 0s, 1s, and 2s, then overwrote the original array using those counts. Because the frequency array never grows beyond 3 elements regardless of input size, the space stays constant. There is something satisfying about coming back to a problem that once stumped you and seeing it clearly this time. It is proof that the reps are adding up even when it does not feel like it in the moment. #100DaysOfCode #LeetCode #NeetCode #DataStructures #Arrays #CodingJourney #ProblemSolving #Programming #SoftwareEngineering #Tech

To view or add a comment, sign in

Explore content categories