LeetCode 347: Top K Frequent Elements
Understanding LeetCode 347: Find the Most Frequent K Elements

I'm Varchasv, a Data Engineer working on enterprise data integration.
Currently on a 90-problem challenge to level up my technical skills and switch to a more development-focused role.
What I'm doing:
- Solving 2 Leetcode problems daily (SQL + DSA).
- Blogging about each problem.
- Building in public.
My Goal - Land a better data engineering role by mid-2026.
Follow my journey !!
Date: January 19, 2026
Category: Array | HashMap | Bucket Sort
Time Taken: 45 minutes
Difficulty: Medium
Problem Statement
Given an integer array nums and an integer k, return the k most frequent elements.
Link: Top K Frequent Elements
My Approach
Initial thought: I was unable to think up of any solution.
Final solution:
First, create a HashMap
counterthat will count the occurrences of all the numbers in thenumslist and use a for loop to count them or can useCollections.Counter.After this, create
freqa list of lists that will store all the numbers that appeared times equal to index as a list. Fix the length offreqto be equal tolen(nums) + 1.Create a list
resultListthat will store all the top k elements, we will start the for loop at the end offrequntil we reach 0 index. Inside this make another for loop that will loop in the internal list offreqand append the numbers in to theresultList.
This is called Bucket Sort solution.
Solution Code (Bucket Sort)
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# Hashmap to count the occurences of each element
counter = {}
for num in nums:
counter[num] = counter.get(num, 0) + 1
# List of List to store the elements that occur a particular time, of total length = len(nums) + 1
freq = [[] for i in range(len(nums) + 1)]
for number, frequency in counter.items():
freq[frequency].append(number)
# Result list that will have the top k elements
resultList = []
for i in range(len(freq) - 1, 0, -1):
for num in freq[i]:
resultList.append(num)
if len(resultList) == k:
return resultList
Complexity:
Time: O(N + N + N) = O(N)
Space: O(N)
Key Takeaway: Bucket Sorting algorithm.
Pattern: Top K Elements
Mistakes I Made: Did not even figure out a brute force solution.
Series: 90 Days of Data Engineering Progress: 10/90 problems completed
Tags: #DEQuest #LeetCode #Python #DataEngineering #BuildInPublic