Practice
Solution
Step 1: Understand frequency distribution
Counting frequencies is straightforward, but sorting all words fully costs O(n log n).Step 2: Use bucket sort to group words by frequency
Bucket sort groups words by frequency in O(n), then sorting lex order within buckets is efficient since buckets are smaller.Final Answer:
Option D -> Option DQuick Check:
Bucket sort + lex sort within buckets achieves O(n) time [OK]
- Assuming full sort is optimal
- Using DP for frequency counting
- Greedy without sorting fails tie-break
Solution
Step 1: Identify partition logic
Partition should move elements greater than pivot to the left for kth largest.Step 2: Locate bug
The condition uses '<' instead of '>', reversing the order and breaking correctness.Final Answer:
Option A -> Option AQuick Check:
Incorrect comparison flips partition logic [OK]
- Using wrong comparison direction in partition
- Confusing base case with recursion
- Swapping wrong elements
Solution
Step 1: Identify loops and heap operations
The algorithm iterates over all m*n coordinates, computing prefix XOR in O(1) per cell.Step 2: Analyze heap operations per coordinate
For each coordinate, heap operations (push or replace) take O(log k) time, since heap size is limited to k.Final Answer:
Option B -> Option BQuick Check:
Overall complexity is O(m * n * log k), not O(m * n * k) or O(m^2 * n^2) [OK]
- Confusing k with n or m
- Assuming sorting all values is needed
- Ignoring heap operation cost
Solution
Step 1: Understand duplicates impact
Duplicates must be treated as distinct points; Quickselect partitions by distance and does not rely on uniqueness.Step 2: Modify partition to handle duplicates correctly
Partition logic remains the same; all points, including duplicates, are compared and placed correctly without skipping.Final Answer:
Option D -> Option DQuick Check:
Quickselect handles duplicates naturally if partitioning is correct [OK]
- Using min heap instead of max heap
- Removing duplicates before selection
- Sorting all points unnecessarily
Solution
Step 1: Understand infinite reuse impact
Infinite reuse means frequency counts are not fixed; problem becomes combinatorial.Step 2: Recognize problem class change
Top k frequent words with unlimited reuse resembles knapsack or coin change, not simple frequency counting.Step 3: Bucket sort no longer applies
Bucket sort relies on fixed frequencies; dynamic programming or other combinatorial methods are needed.Final Answer:
Option A -> Option AQuick Check:
Infinite reuse breaks frequency counting assumptions [OK]
- Trying to reuse bucket sort with infinite counts
- Ignoring combinatorial explosion
- Assuming heap approach suffices
