Sort Characters by Frequency in Java

Day - 39 Sort Characters by Frequency The problem - Given a string s, sort it in decreasing order based on the frequency of characters. Return the sorted string. Example : s = "tree" → "eert" or "eetr" s = "cccaaa" → "aaaccc" or "cccaaa" Brute force - Count the frequencies of characters in both strings and then sort manually, but the time complexity will be O(n log n). Approach Used - •) Create HashMap to count character frequencies, iterate through the s.toCharArray() and use hm.put(char, hm.getOrDefault(char, 0) + 1). •) Create max heap PriorityQueue with custom comparator, PriorityQueue<Map.Entry<Character, Integer>> pq. •) And the comparator = (a, b) → b.getValue() - a.getValue(). •) Add all entries from HashMap - pq.addAll(hm.entrySet()). •) While pq is not empty. 1 - Poll entry from pq. 2 - Append character repeated by its frequency, String.valueOf(entry.getKey()).repeat(entry.getValue()). •) Return result.toString(). Complexity - Time - O(n + k log k), where n is string length, k is unique characters. Space - O(n), HashMap and result. Note - PriorityQueue with reverse comparator gives us characters in frequency order automatically. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories