← Deloitte bank

Deloitte · Question 56 · Heaps

Top K Frequent Elements

HeapsJavacode⏱ O(n)💾 O(n)
Service-based

Problem

Return k elements with highest frequency.

Approach

Use bucket sort by frequency (O(n)) or a heap.

Time O(n)Space O(n)

How it works

  1. 1Count frequencies.
  2. 2Bucket values by frequency; read top-down.

Sample input / output

Input:
nums = [1, 1, 1, 2, 2, 3], k = 2
Output:
[1, 2]

Constraints

Answer unique; k valid.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 4Branches 3Returns 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> m =new HashMap<>()for (int n : nums)m.put(n,m.getOrDefault(n, 0) …List<Integer>[] buckets =new List[nums.length + 1]for (int key :m.keySet())DEFINE f = m.get(key)if (buckets[f] ==null) buckets[f] = newArrayList<>()buckets[f].add(key)DEFINE [] res = new int[k]DEFINE idx = 0for (int i =buckets.length - 1; i>= 0 && idx < k; i--)if (buckets[i] !=null)for (int v :buckets[i])res[idx++] = vif (idx == k) breakRETURN resDEFINE static voidmain(String[] args)System.out.println(Arrays.toString(topKFrequent(newint[]{1, 1, 1, 2, 2, 3},2)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

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