DSA interview question
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].
static List<Map.Entry<String, Integer>> topKFrequent(List<String> words, int k);
// sorted by count descending, then word ascending; at most k entries
Input (words, k) | Output | Explanation |
|---|---|---|
(["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.)
HashMap vs TreeMap?", "ArrayList vs LinkedList?", "How does HashMap work internally?", "Why override hashCode when you override equals?"HashMap vs TreeMap?"HashMap work?"equals and hashCode agree?"ArrayList vs LinkedList?"Integer.compare instead of subtracting in a comparator?"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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in