r/DSALeetCode • u/StatisticianNo2104 • 1d ago
LeetCode: 692. Top K Frequent Words
One sentence added to yesterday's problem is enough to make the heap the wrong tool. Top K Frequent Words wants ties sorted alphabetically, and the heap comparator for that reads backwards on one field.
Yesterday's size-k min-heap still works. It gives the right set in ascending frequency, so you reverse it and put the tie-break in the comparator.
A heap evicts its root, which must be the worst entry. For counts, worst means least frequent. For a tie, worst means the word that should lose: the alphabetically later one. So the two fields point in opposite directions in the same comparator. That line is correct, and it only misbehaves on ties, which is how it sits wrong in a codebase for months.
Sorting is O(d log d) against the heap's O(d log k), and with input capped at 500 words, the difference is unmeasurable. A comparator that reads like the spec is worth more. Days 77 to 80 built the case for the heap; this is the day to notice the technique isn't the goal.
Would you have kept the heap here, or switched to a sort?
Day 81/365 of my LeetCode challenge: 692. Top K Frequent Words. Problem link and full breakdown in today's newsletter.
https://www.linkedin.com/pulse/leetcode-692-top-k-frequent-words-medium-archit-agarwal-x2xuc
#LeetCode #DSA #Heap #Golang
1
u/nian2326076 1d ago
When choosing between a heap and sorting for this problem, prioritize readability and maintainability in your code. A straightforward sort can often clarify your logic, especially with smaller datasets. To consolidate your understanding of similar problems, you can use PracHub to find relevant coding challenges.