Medium Problems

347. Top K Frequent Elements

Solutions

function topKFrequent(nums: number[], k: number): number[] {
  let map = new Map();
 
  for (let i = 0; i < nums.length; i++) {
      let num = nums[i]
      if(map.has(num)) {
          map.set(num, map.get(num) + 1)
      } else {
          map.set(num, 1)
      }
  }
 
  let buckets = Array.from({ length: nums.length + 1}, (v,k) => k).map(_ => [])
  map.forEach((value, key) => {
      buckets[value].push(key) 
  })
 
  let res = [];
  for(let i = buckets.length - 1; i > 0; i--) {
      for(let j = 0; j < buckets[i].length; j++) {
          res.push(buckets[i][j])
          if(res.length === k) return res;
      }
  }
};

Video Solution

...I really like this problem, because it's pretty clever, and once you figure it out, the code is really easy to write.

Last Update: 11:43 - 16 April 2024
Array
Hash Table
Divide and Conquer
Sorting
Heap (Priority Queue)
Bucket Sort
Counting
Quickselect

On this page