Home › Company-wise questions › Microsoft › Top K Frequent Elements ← Microsoft bank
Microsoft · Question 55 · Heaps
Top K Frequent Elements Heaps Java code ⏱ O(nlogk) 💾 O(n)
Product-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 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 Count every value's frequency. 2 A 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 Flowchart Pseudocode
Time O(nlogk)Space O(n)Loops 4Branches 1Returns 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> 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 res DEFINE static void main(String[] args) java.util.Scanner sc = new java.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← Q54 · Sort an Array Q56 · Fibonacci Number → 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 →