PPractick

DSA interview question

Java Collections: Top K Frequent Words

Easy · Algorithms · Topics: collections, java

The problem

The same leaderboard as in the C++ STL exercise, but your team's backend is in Java: count the words users search for and return the k most frequent, with ties broken alphabetically. The task doubles as a tour of the Java Collections Framework that interviews in Java assume you know: HashMap for counting, ArrayList and List.sort with a Comparator for ranking, plus TreeSet, PriorityQueue, ArrayDeque and TreeMap.

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

Function signature

static List<Map.Entry<String, Integer>> topKFrequent(List<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=2]Highest counts first
(["b","a","c","a","b","c"], 3)[a=2, b=2, c=2]All tied, alphabetical
(["x"], 5)[x=1]Fewer distinct words than k
(["dog","cat","dog"], 1)[dog=2]Only the top entry

(Confirm: ties are broken alphabetically; return every word if there are fewer than k.)

How interviewers phrase it

Clarifying questions to ask

  1. Tie-breaking order?
  2. Fewer than k distinct words: return all?
  3. Case-sensitive?
  4. Is the input large enough that a heap would beat a full sort?

Follow-ups to expect

  1. "HashMap vs TreeMap?"
  2. "How does HashMap work?"
  3. "Why must equals and hashCode agree?"
  4. "ArrayList vs LinkedList?"
  5. "How do you make a max-heap?"
  6. "Why Integer.compare instead of subtracting in a comparator?"

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