Home › Interview Questions › Rewrite the following top_k_words function to find…

Rewrite the following top_k_words function to find the top k words without using any imports such as heapq or Counter.

🟡 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

You can implement the same logic with only built‑in data structures. First split the text into words. Then iterate over the list, updating a plain dictionary that maps each word to its count. After counting, convert the dictionary items to a list and sort it by the count in descending order. Finally, slice the first k elements. This approach runs in O(n log n) time due to the sort, and uses O(m) additional space where m is the number of distinct words. Example code: def top_k_words(text, k=5): words = text.split(); counts = {}; for w in words: counts[w] = counts.get(w, 0) + 1; return sorted(counts.items(), key=lambda x: x[1], reverse=True)[:k] The sorted function uses Timsort, which is stable and efficient. If you need better than O(n log n) for very large data, you could implement a min‑heap manually, but that would require more code. For most interview scenarios, the dictionary‑plus‑sort solution is acceptable and demonstrates clear understanding of counting and sorting. This solution is straightforward to understand and easy to implement, making it a common interview answer for counting problems.

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