← Accenture bank

Accenture · Question 44 · Heaps

Top K Frequent Words

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

Problem

Given a list of words and an integer k, return the k most frequent words. If multiple words have same frequency, return lexicographically smallest first.

Approach

Use hashmap to count frequency, then a custom comparator with priority queue.

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

How it works

  1. 1Count word frequencies.
  2. 2Heap orders by frequency, ties broken lexically.

Sample input / output

Input:
words = ["i", "love", "codeleet", "i", "love", "coding"], k = 2
Output:
[i, love]

Constraints

1 <= words.length <= 500; lowercase words; answer unique.

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 <string>include <vector>include <unordered_map>include <queue>include <algorithm>using namespace stdvector<string>topKFrequentWords(vector<string>&words, int k)DEFINE main()vector<string> words ={"i", "love", "codeleet","i", "love", "coding"}auto r =topKFrequentWords(words, 2)cout << "["for (size_t i = 0; i <r.size(); ++i)if (i) cout << ", "cout << r[i]cout << "]" << endlRETURN 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