#347
Top K Frequent Elements
medium· Arrays & Hashingruns: 0Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. The algorithm should run in O(n) time.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 542
class Solution:
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
result = []
for freq in range(len(buckets) - 1, 0, -1):
for num in buckets[freq]:
result.append(num)
if len(result) == k:
return result
return result
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.