← All writing
Development

[Leetcode] Top K Frequent Elements

Top K Frequent Elements

leetcode link

Given an integer array <span style="font-size: 0.75rem;">nums</span>and an integer <span style="font-size: 0.75rem;">k</span>, return the <span style="font-size: 0.75rem;">k</span>most frequent elements. You may return the answer in any order.

Example 1:

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

Example 2:

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

Constraints:

  • <span style="font-size: 14px;">1 <= nums.length <= 10<sup>5</sup></span>

  • <span style="font-size: 14px;">-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></span>

  • <span style="font-size: 14px;">k is in the range [1, the number of unique elements in the array].</span>

  • <span style="font-size: 14px;">It is guaranteed that the answer is unique.</span>

<span style="font-size: 20px;">how to approach</span>

  1. <span style="font-size: 14px;">set the Map to check the element in array.</span>

  2. <span style="font-size: 14px;">and in for loop, add the element one by one to check the count.</span>

  3. <span style="font-size: 14px;">after that, sort out the array from the map so it can have the order by element count.</span>

  4. <span style="font-size: 14px;">return the sliced array for top K frequent elements.</span>

function topKFrequent(nums: number[], k: number): number[] {
    let frequent = new Map()
    
    for(let num of nums){
        let count = frequent.get(num) || 0
        frequent.set(num,count + 1)
    }
    
    let sorted = Array.from(frequent)
                      .sort((a,b)=>b[1]-a[1])
                      .slice(0,k)
                      .map(([num])=>num)
  
    return sorted
};

summary

this leetcode problem is solved by typescript language.

the approach is using Map that has key and value in it, set key as element itself and value as counted number of how many elements was in the array.

and lastly sorting the array from counted number of the elements and slice them by the K input to figure out the top K frequent elements in the array.