Practice: heaps and tries
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Master problem-solving patterns using heaps and tries for string reorganization, sorted matrix search, XOR, and prefix replacement.
Reorganising strings and sorted matrix search
Reorganise String rearranges letters so no two neighbours match, using a greedy max-heap. Kth smallest in a sorted matrix uses a min-heap seeded with the first value of each row.
Example 1 · Reorganise String Using Max-Heap
import java.util.*;
public class Main { static String reorganizeString(String s) { int[] counts = new int[26]; for (char c : s.toCharArray()) counts[c - 'a']++;
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b[1], a[1])); for (int i = 0; i < 26; i++) { if (counts[i] > 0) { if (counts[i] > (s.length() + 1) / 2) return ""; maxHeap.offer(new int[]{i, counts[i]}); } }
StringBuilder sb = new StringBuilder(); int[] prev = null; while (!maxHeap.isEmpty()) { int[] cur = maxHeap.poll(); sb.append((char) ('a' + cur[0])); cur[1]--;
if (prev != null && prev[1] > 0) { maxHeap.offer(prev); } prev = cur; } return sb.toString(); }
public static void main(String[] args) { System.out.println("Result 'aab': " + reorganizeString("aab")); System.out.println("Result 'aaab': '" + reorganizeString("aaab") + "'"); }}Result 'aab': aba Result 'aaab': ''
What this code does
- Counts track character frequencies.
- If any character exceeds (n + 1) / 2, impossible to rearrange.
- prev holds the last placed character until another is chosen, preventing duplicates.
Example 2 · Brute force: flatten and sort, O(n^2 log n) time, O(n^2) space
import java.util.*;
public class Main { public static void main(String[] args) { int[][] matrix = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}}; int k = 8; List<Integer> all = new ArrayList<>(); for (int[] row : matrix) { for (int v : row) all.add(v); } Collections.sort(all); System.out.println("kth smallest: " + all.get(k - 1)); }}kth smallest: 13
What this code does
- Every value of the n by n matrix is copied into one list, so extra space is O(n^2).
- Sorting the list ignores that rows and columns are already sorted.
- The heap version reads only the first k values it needs.
Example 3 · Optimal: min-heap of row heads, O(k log n) time, O(n) space
import java.util.Comparator;import java.util.PriorityQueue;
public class Main { static int kthSmallest(int[][] matrix, int k) { int n = matrix.length; PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
for (int r = 0; r < Math.min(n, k); r++) { pq.offer(new int[]{matrix[r][0], r, 0}); }
for (int i = 0; i < k - 1; i++) { int[] cur = pq.poll(); int r = cur[1], c = cur[2]; if (c + 1 < matrix[r].length) { pq.offer(new int[]{matrix[r][c + 1], r, c + 1}); } } return pq.peek()[0]; }
public static void main(String[] args) { int[][] mat = { {1, 5, 9}, {10, 11, 13}, {12, 13, 15} }; System.out.println("8th smallest: " + kthSmallest(mat, 8)); }}8th smallest: 13
What this code does
- Min-heap holds row heads, starting with the first column.
- Polling k - 1 times discards smaller elements in ascending order.
- The kth polled element gives the exact matrix value in O(k log n) time.
- It is faster because only the current head of each row is in the heap, so k polls are enough instead of sorting n * n values.
For reorganising: if any character appears more than (n + 1) / 2 times the task is impossible. Otherwise keep letter counts in a max-heap, poll the most frequent letter, append it, and hold it back for one step before pushing it again.
For the matrix: poll the minimum k times, each time pushing the next value from the same row, for O(k log rows) time.
Bit tries for maximum XOR and word replacement
Finding the pair of numbers with the maximum XOR by brute force checks every pair in O(n^2). A bit trie stores each number as a path of 0 and 1 branches and answers in about O(32 * n).
Example 4 · Replace Words with Trie Prefixes
import java.util.*;
public class Main { static class TrieNode { TrieNode[] next = new TrieNode[26]; String word = null; }
static String replaceWords(List<String> dict, String sentence) { TrieNode root = new TrieNode(); for (String w : dict) { TrieNode cur = root; for (char c : w.toCharArray()) { int i = c - 'a'; if (cur.next[i] == null) cur.next[i] = new TrieNode(); cur = cur.next[i]; } cur.word = w; }
StringBuilder sb = new StringBuilder(); for (String token : sentence.split(" ")) { if (sb.length() > 0) sb.append(" "); TrieNode cur = root; String replacement = token; for (char c : token.toCharArray()) { int i = c - 'a'; if (cur.next[i] == null || cur.word != null) break; cur = cur.next[i]; } if (cur.word != null) replacement = cur.word; sb.append(replacement); } return sb.toString(); }
public static void main(String[] args) { List<String> roots = Arrays.asList("cat", "bat", "rat"); String sent = "the cattle was rattled by the battery"; System.out.println(replaceWords(roots, sent)); }}the cat was rat by the bat
What this code does
- Prefix roots are inserted into the trie.
- Words in sentence traverse the trie until finding the earliest root.
- cattle becomes cat, rattled becomes rat, and battery becomes bat.
Insert each number as a 31-bit path. For a number X, walk down choosing the opposite bit at every level whenever that branch exists.
The same practice includes replacing words with their shortest root: insert all roots in a trie, walk each word until the first node marked isWord, and replace the word with that prefix.
Decision framework: choosing heaps, tries, or hash tables
Choose a heap when problems require extreme values, top-k selections, running medians, or chronological event scheduling. Heaps excel at maintaining partial order over dynamic data streams in O(log n) time.
Choose a trie when tasks involve prefix matching, autocomplete suggestions, dictionary roots, or binary bitwise XOR lookups. Tries excel when strings share common prefixes and search cost must depend solely on word length L.
Choose a hash table when problems require exact key lookups in expected O(1) time without prefix needs.
Finish up
Mark complete & continue
Next: What a graph is