Python solution three lines 52ms (~beat 92%)

  • 0
    import collections
    class Solution(object):
        def topKFrequent(self, words, k):
            :type words: List[str]
            :type k: int
            :rtype: List[str]
            counts = collections.Counter(words)   
            freqs = sorted((-count, word) for word, count in counts.items())
            return [f[1] for f in freqs[:k]]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.