How would you find the top 5 most frequent words in a given text using a hash map?
💡 Model Answer
To find the top 5 most frequent words, first split the text into words (e.g., using regex or split on whitespace). Use a dictionary (hash map) to count each word: increment the count for each occurrence. After counting, you need the five words with the highest counts. Two common approaches are: 1) Sort the items by count in descending order and slice the first five. This is O(n log n) time and O(k) space, where k is the number of unique words. 2) Use a min‑heap of size 5. Iterate over the dictionary items; push each (count, word) onto the heap, and if the heap grows larger than 5, pop the smallest. This keeps only the top 5 in memory and runs in O(n log 5) ≈ O(n) time. Finally, return the words from the heap or the sorted slice. In Python, you can use collections.Counter and its most_common(5) method for a concise solution. Complexity: O(n) time for counting plus O(n log 5) for the heap, and O(k) space for the dictionary.
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