I was checking out this solution to a question on leetcode.com
def topKFrequent(self, words, k):
count = collections.Counter(words)
heap = [(-freq, word) for word, freq in count.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in xrange(k)]
and when I provide it an array of strings like ["aa", "aaa", "a"]
and 1
it correctly returns ["a"]
. My question is did the heap also lexographically sort the tuples internally? Because according to me if there was no sorting, it would have simply returned ["aa"]
(the order in which the heap was constructed since counts of all three are the same). Or have I misunderstood heapq
?