← Google bank

Google · Question 12 · Heaps

Top K Frequent Elements

HeapsPythoncode⏱ O(nlogk)💾 O(n)
Product-based

Problem

Return the k most frequent elements in the array.

Approach

Use a hashmap for frequency count and a heap to extract the top k.

Time O(nlogk)Space O(n)

How it works

  1. 1Count the frequency of each element using Counter.
  2. 2Use heapq.nlargest to get the top k keys by frequency.
  3. 3Return those keys.
  4. 4This finds the top k without sorting the entire list.

Sample input / output

Input:
6 2
1 1 1 2 2 3
Output:
[1, 2]

Constraints

1 <= nums.length <= 10^5; -10^4 <= nums[i] <= 10^4; 1 <= k <= unique elements; answer is unique.

Solution — read it, then walk it

Time O(nlogk)Space O(n)Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoSTARTfrom collections importCounterimport heapqDEFINE topKFrequent(nums,k)count = Counter(nums)RETURN heapq.nlargest(k,count.keys(),key=count.get)DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); k =int(next(it))nums = [int(next(it)) for _in range(n)]print(topKFrequent(nums,k))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/15

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits