Finding most frequent element is also a classic interview question. Here's my javascript solution for this leecode exercise problem.


Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

For submission or more details about Top K Frequent Elements problem


  • Create a hashmap with all the value and their occurrences
  • Sort the frequency and return the k frequencies
  • Take items having those frequencies