← Accenture bank

Accenture · Question 43 · Heaps

Top K Frequent Elements

HeapsC++code⏱ O(n log k)💾 O(n)
Service-based

Problem

Given an integer array nums and an integer k, return the k most frequent elements.

Approach

Count frequency with hashmap, use a min - heap (priority queue) to keep top k.

Time O(n log k)Space O(n)

How it works

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

Sample input / output

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

Constraints

Answer unique; driver prints most-frequent-first.

Solution — read it, then walk it

Time O(n log k)Space O(n)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>include <unordered_map>include <queue>include <algorithm>using namespace stdvector<int>topKFrequent(vector<int>&nums, int k)DEFINE printVec(constvector<int>& v)cout << "["for (size_t i = 0; i <v.size(); ++i)if (i) cout << ", "cout << v[i]cout << "]" << endlDEFINE main()vector<int> nums = {1, 1,1, 2, 2, 3}printVec(topKFrequent(nums,2))RETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

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