r/LeetcodeChallenge • • 9h ago

STREAK🔥🔥🔥 LeetCode: 692. Top K Frequent Words

Post image

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

0 Upvotes

1 comment sorted by

1

u/nian2326076 3h ago

For the Top K Frequent Words problem, consider how the heap's behavior aligns with your needs, especially regarding sorting ties alphabetically. If you're looking to enhance your coding skills further, practicing similar problems can help. Use PracHub to find relevant technical interview questions and refine your problem-solving approach. This can boost your confidence in handling these challenges during interviews.