Learning on Web Dev Open is free for all.

Interview Prep · CodeTop k most frequent elements
← Code

Top k most frequent elements

Medium25 minFree, no account

Sorting works. The question is whether you can beat it, and whether you know when not to bother.


The question

Given an array and a number k, return the k most frequent elements.

Give the complexity of your approach, and say what you would do if the array did not fit in memory.

topK([1,1,1,2,2,3], 2)        // [1, 2]
topK(["a","b","a","c","b","a"], 1)  // ["a"]
25:00Commit to an answer before you open the solution. Reading it first teaches you to recognise good answers, which is not the skill being tested.

Stuck?

0 of 3 hints taken

The worked solution

written by a person · not a grade

Score yourself

0 of 5 marked
  • Correct counting and a working top-k25
  • Gave more than one approach with honest complexities25
  • Produced the O(n) bucket solution and stated its precondition25
  • Distinguished n from m in the analysis15
  • Had an answer for data that does not fit in memory10

We run no AI here and nothing on this page grades you. The score is yours, and the useful number is the one you get on the same problem a month from now, cold.

kept in this browser only