← PayPal bank

PayPal · Question 51 · Heaps

Top K Frequent Elements

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

Problem

Return the k most frequent elements from an array.

Approach

Use a frequency map and a min - heap priority queue to track top k elements.

Time O(nlogk)Space O(n)

How it works

  1. 1Count frequencies.
  2. 2A size-k min-heap keeps the top entries, most frequent last polled.

Sample input / output

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

Constraints

Answer unique; any order accepted by the judge; driver prints most-frequent-first.

Solution — read it, then walk it

Time O(nlogk)Space O(n)Loops 3Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]topKFrequent(int[] nums,int k)Map<Integer, Integer> count= new HashMap<>()for (int num : nums)count.put(num,count.getOrDefault(num…PriorityQueue<Integer> heap= new PriorityQueue<>((n1,n2) -> count.get(n1) …for (int num :count.keySet())heap.offer(num)if (heap.size() > k)heap.poll()DEFINE [] result = newint[k]for (int i = k - 1; i>= 0; i--) result[i] =heap.poll()RETURN resultDEFINE 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/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