← Microsoft bank

Microsoft · Question 55 · Heaps

Top K Frequent Elements

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

Problem

Return the k most frequent elements in the array.

Approach

Count frequencies, keep the top k in a min-heap.

Time O(nlogk)Space O(n)

How it works

  1. 1Count every value's frequency.
  2. 2A size-k min-heap keeps the top entries.

Sample input / output

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

Constraints

1 <= nums.length <= 10^5; answer unique; any order accepted.

Solution — read it, then walk it

Time O(nlogk)Space O(n)Loops 4Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]topKFrequent(int[] nums,int k)Map<Integer, Integer> freq= new HashMap<>()for (int num : nums)freq.put(num,freq.getOrDefault(num, 0) +1)PriorityQueue<Map.Entry<Integer,Integer>> heap =for(Map.Entry<Integer,Integer> entry …heap.offer(entry)if (heap.size() > k)heap.poll()DEFINE [] res = new int[k]for (int i = 0; i < k;i++)res[i] =heap.poll().getKey()RETURN resDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt();int k = sc.nextInt()DEFINE [] nums = new int[n]for (int i = 0; i <nums.length; i++)nums[i] = sc.nextInt()System.out.println(Arrays.toString(topKFrequent(nums,k)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

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