Improved Frequency Sort in Java with O(N) Counting

Day 80 of #100DaysOfCode Solved Frequency Sort in Java 🔠 Approach Today's problem was to sort an array based on the frequency of its numbers. My initial solution was accepted, but it exposed a major efficiency gap! My strategy involved: Sorting the array first. Using nested loops to count the frequency of each number and store it in a HashMap. (Implied) Using the counts to perform the final custom sort. The core issue was the counting method: running a full loop inside another full loop to get the frequency. This quadratic $O(N^2)$ counting completely tanked the performance. ✅ Runtime: 29 ms (Beats 12.02%) ✅ Memory: 45.26 MB (Beats 5.86%) Another great lesson in algorithmic complexity! The difference between $O(N^2)$ and the optimal $O(N \log N)$ for this problem is massive. Time to refactor and implement the fast, single-pass $O(N)$ frequency count using getOrDefault! 💪 #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #HashMap #Optimization #ProblemSolving

  • graphical user interface

To view or add a comment, sign in

Explore content categories