Home › Company-wise questions › Deloitte › Top K Frequent Elements ← Deloitte bank
Deloitte · Question 56 · Heaps
Top K Frequent Elements Heaps Java code ⏱ O(n) 💾 O(n)
Service-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Count frequencies. 2 Bucket 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 Flowchart Pseudocode
Time O(n)Space O(n)Loops 4Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat yes ↻ repeat ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE 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] = new ArrayList<>() buckets[f].add(key) DEFINE [] res = new int[k] DEFINE idx = 0 for (int i = buckets.length - 1; i >= 0 && idx < k; i--) if (buckets[i] != null) for (int v : buckets[i]) res[idx++] = v if (idx == k) break RETURN res DEFINE static void main(String[] args) System.out.println(Arrays.toString(topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2))) END start / end statement condition loop returns definition← Q55 · K Closest Points to Origin Q57 · Topological Sort / Course Schedule (II) → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →