Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.



Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.



Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.



Follow up:

Try to solve it in O(n log k) time and O(n) extra space.

Source: leetcode | Difficulty: MEDIUM_HARD
Tags: String algorithms

Sorting

Data structures

Mathematics

Starter code: class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        

Solutions:
class Solution:

	def topKFrequent(self, words, k):
		from collections import Counter
		count = Counter(words)
		common = sorted(list(count.items()), key=lambda item: (-item[1], item[0]))[:k]
		return [w for (w, n) in common]


class Solution:

	def topKFrequent(self, words, k):
		d = {}
		for word in words:
			d[word] = d.get(word, 0) + 1
		ret = sorted(d, key=lambda word: (-d[word], word))
		return ret[:k]


class Solution:

	def topKFrequent(self, words, k):
		from collections import Counter
		return [item[0] for item in sorted(Counter(words).items(), key=lambda x: (-x[1], x[0]))[:k]]


class Solution:

	def topKFrequent(self, words, k):
		cnt = collections.Counter(words)
		word_freq = list(cnt.items())
		word_freq.sort(key=lambda item: (-item[1], item[0]))
		return [k for (k, v) in word_freq[:k]]


class Solution:

	def topKFrequent(self, words, k):
		cnt = {i: words.count(i) for i in list(set(words))}
		cntRev = {}
		ans = []
		for (key, val) in cnt.items():
			if val not in cntRev:
				cntRev[val] = [key]
			else:
				cntRev[val].append(key)
		for num in sorted(cntRev, reverse=True):
			if k <= len(cntRev[num]):
				ans += sorted(cntRev[num])[:k]
				break
			else:
				ans += sorted(cntRev[num])
				k -= len(cntRev[num])
		return ans


class Solution:

	def topKFrequent(self, words, k):
		times_dict = {}
		for i in words:
			if i not in times_dict.keys():
				times_dict[i] = 1
			else:
				times_dict[i] += 1
		return_list = []
		for i in range(k):
			max = 0
			max_key = ''
			for j in times_dict.keys():
				if times_dict[j] > max:
					max = times_dict[j]
					max_key = j
				elif times_dict[j] == max and j < max_key:
					max = times_dict[j]
					max_key = j
			del times_dict[max_key]
			return_list.append(max_key)
		return return_list


class Solution:

	def topKFrequent(self, words, k):
		counter = collections.Counter(words)
		keys = list(counter.keys())
		keys.sort(key=lambda x: (-counter[x], x))
		return keys[:k]


class Solution:

	def topKFrequent(self, words, k):
		counts = collections.Counter(words)
		items = list(counts.items())
		items.sort(key=lambda item: (-item[1], item[0]))
		return [item[0] for item in items[0:k]]


class Solution:

	def topKFrequent(self, words, k):
		c = collections.Counter(words).most_common()
		res = []
		while len(res) < k:
			temp = []
			node = c.pop(0)
			temp.append(node[0])
			while c and c[0][1] == node[1]:
				node = c.pop(0)
				temp.append(node[0])
			res.extend(sorted(temp))
		return res[:k]


class Solution:

	def topKFrequent(self, words, k):
		wDict = collections.Counter(words)
		res = []
		maxHeap = []
		for (key, cnt) in list(wDict.items()):
			heapq.heappush(maxHeap, (-cnt, key))
		for i in range(k):
			(freq, word) = heapq.heappop(maxHeap)
			res.append(word)
		return res