How would you find the top 5 most frequent words in a string using a hash map and a min‑heap?
💡 Model Answer
To find the top 5 most frequent words in a string, you can use a hash map (Python dictionary) to count occurrences and a min‑heap of size 5 to keep the current top words. First, split the string into words, normalizing case and stripping punctuation. Iterate over the words, incrementing the count in the dictionary. Then iterate over the dictionary items: for each (word, count), push the pair onto the heap. If the heap size exceeds 5, pop the smallest element. After processing all items, the heap contains the 5 words with the highest counts. The heap operations are O(log k) where k=5, so the overall time is O(n log k) ≈ O(n). Memory usage is O(m + k), where m is the number of distinct words. In Python, you can use heapq.nsmallest or heapq.nlargest to simplify the logic. This approach is efficient when the number of distinct words is large, as it avoids sorting the entire dictionary. It also handles ties by keeping the first encountered word when counts are equal, unless you explicitly define a tie‑breaking rule.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500