[NeetCode] Top K Elements In List
Synced attempt history for Top K Elements In List.
0
Tags: algorithms, neetcode, python
Categories: NeetCode
- Problem
- Synced automatically from
devbattery/neetcode-submissions
Notes
Write your own notes here. This section is preserved across syncs.
Attempts
Attempt 1 · 2026-05-20 · Python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
cnt_dict = collections.Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)] # 0 to len(nums)
for num, freq in cnt_dict.items():
buckets[freq].append(num)
answer = []
for i in range(len(buckets) - 1, 0, -1):
for num in buckets[i]:
answer.append(num)
if k == len(answer):
return answer
Attempt 2 · 2026-05-20 · Python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
cnt_dict = collections.Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)] # 0 to len(nums)
for num, freq in cnt_dict.items():
buckets[freq].append(num) # num by freq
answer = []
for i in range(len(buckets) - 1, 0, -1):
for num in buckets[i]:
answer.append(num)
if k == len(answer):
return answer
Leave a comment