Min-heap approach for time.
function topKFrequent(words, k):
freq = {}
for word in words:
freq[word] = freq.getOrDefault(word, 0) + 1
// Min-heap: lower freq = smaller. At equal freq, later alphabetical = smaller.
minHeap = new MinHeap(comparator)
for (word, count) in freq:
minHeap.push((count, word))
if minHeap.size() > k:
minHeap.pop()
result = []
while minHeap is not empty:
(count, word) = minHeap.pop()
result.append(word)
return result.reverse()
The comparator for the min-heap: compare by frequency ascending first. If frequencies are equal, compare by word descending (reverse alphabetical). This way, the "least desirable" entry stays on top and gets evicted when the heap exceeds size k.