|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +// Problem: Sort Characters By Frequency |
| 4 | +// Pattern: HashMap + Priority Queue (Heap) |
| 5 | +// Difficulty: Medium |
| 6 | + |
| 7 | +/* |
| 8 | + Approach: |
| 9 | + 1. Count frequency of each character using a HashMap. |
| 10 | + 2. Store characters in a max-heap (PriorityQueue) based on frequency. |
| 11 | + 3. If frequencies are same, sort by character (lexicographically). |
| 12 | + 4. Extract from heap and append characters 'frequency' times. |
| 13 | +
|
| 14 | + Time Complexity: O(n log n) |
| 15 | + Space Complexity: O(n) |
| 16 | +*/ |
| 17 | + |
| 18 | +class Solution { |
| 19 | + public String frequencySort(String s) { |
| 20 | + |
| 21 | + // Step 1: Count frequency of each character |
| 22 | + Map<Character, Integer> map = new HashMap<>(); |
| 23 | + |
| 24 | + for (int i = 0; i < s.length(); i++) { |
| 25 | + char ch = s.charAt(i); |
| 26 | + |
| 27 | + // Increment frequency using getOrDefault |
| 28 | + map.put(ch, map.getOrDefault(ch, 0) + 1); |
| 29 | + } |
| 30 | + |
| 31 | + // Step 2: Create max-heap based on frequency |
| 32 | + PriorityQueue<Map.Entry<Character, Integer>> pq = |
| 33 | + new PriorityQueue<>((a, b) -> { |
| 34 | + |
| 35 | + // Higher frequency comes first |
| 36 | + int diff = b.getValue() - a.getValue(); |
| 37 | + |
| 38 | + // If frequency same, sort by character |
| 39 | + if (diff == 0) return a.getKey() - b.getKey(); |
| 40 | + |
| 41 | + return diff; |
| 42 | + }); |
| 43 | + |
| 44 | + // Add all entries to heap |
| 45 | + pq.addAll(map.entrySet()); |
| 46 | + |
| 47 | + // Step 3: Build result string |
| 48 | + StringBuilder sb = new StringBuilder(); |
| 49 | + |
| 50 | + while (!pq.isEmpty()) { |
| 51 | + |
| 52 | + Map.Entry<Character, Integer> entry = pq.poll(); |
| 53 | + |
| 54 | + char key = entry.getKey(); // character |
| 55 | + int freq = entry.getValue(); // frequency |
| 56 | + |
| 57 | + // Append character 'freq' times |
| 58 | + for (int i = 0; i < freq; i++) { |
| 59 | + sb.append(key); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Step 4: Return final string |
| 64 | + return sb.toString(); |
| 65 | + } |
| 66 | +} |
0 commit comments