Accenture · Question 44 · Heaps
Top K Frequent Words
Problem
Given a list of words and an integer k, return the k most frequent words. If multiple words have same frequency, return lexicographically smallest first.
Approach
Use hashmap to count frequency, then a custom comparator with priority queue.
Time O(n log k)Space O(n)
How it works
- 1Count word frequencies.
- 2Heap orders by frequency, ties broken lexically.
Sample input / output
Input: words = ["i", "love", "codeleet", "i", "love", "coding"], k = 2 Output: [i, love]
Constraints
1 <= words.length <= 500; lowercase words; answer unique.
Solution — read it, then walk it
Time O(n log k)Space O(n)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/18
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits