PPractick

DSA interview question

C++ STL: Top K Frequent Words

Easy · Algorithms · Topics: stl, collections

The problem

Your team's search box logs every query word, and product wants a small leaderboard of the k most frequent words, with ties broken alphabetically so the list is stable between refreshes. Writing it with raw arrays would mean hand-rolling a hash table and a sort; with the C++ Standard Template Library it takes a few lines. The task is a practical tour of the containers and algorithms you'll use in almost every DSA problem: unordered_map for counting, vector<pair> for results, sort with a custom comparator, and, as a bonus, set, priority_queue, lower_bound and map.

Example: words ["apple", "banana", "apple", "cherry", "banana", "apple"], k = 2 → [("apple", 3), ("banana", 2)].

Function signature

vector<pair<string, int>> topKFrequent(const vector<string>& words, int k);
// sorted by count descending, then word ascending; at most k entries

Test cases

Input (words, k)OutputExplanation
(["apple","banana","apple","cherry","banana","apple"], 2)apple=3 banana=2Highest counts first
(["b","a","c","a","b","c"], 3)a=2 b=2 c=2All tied, so alphabetical order
(["x"], 5)x=1k larger than the number of distinct words
(["dog","cat","dog"], 1)dog=2Only the top entry

(Confirm: 1 ≤ k; ties are broken alphabetically; if there are fewer than k distinct words, return them all.)

How interviewers phrase it

Clarifying questions to ask

  1. How should ties be ordered?
  2. What if there are fewer than k distinct words?
  3. How many words, and how many distinct ones? (Decides whether a full sort or a heap is better.)
  4. Are words case-sensitive?

Follow-ups to expect

  1. "map vs unordered_map?"
  2. "Can you do better than sorting all distinct words?"
  3. "How do you make a min-heap?"
  4. "What does lower_bound do?"
  5. "set vs multiset?"
  6. "What's iterator invalidation?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in