Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created February 9, 2026 23:59
Show Gist options
  • Select an option

  • Save Ephraimiyanda/b15606ca70378c87c5438e1893e34540 to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/b15606ca70378c87c5438e1893e34540 to your computer and use it in GitHub Desktop.
Top K Frequent Elements

Question

Approach

  1. A loop is run to go through each number.
  2. A map is used to check if the number is seen for the first time , if it has not been then the loop skips to the next number.
  3. if a number is seen for the first time a second inner loop is run to check which other number in the array is the same as the current number.
  4. the map is turned into an array of arrays and the k number frequent elements which are the i[0] values are returned.

Complexity

  • Time complexity:O(N^2)

  • Space complexity:O(N)

Code

function topKFrequent(nums: number[], k: number): number[] {
    let n = nums.length
    let result: number[] = []
    let seen = new Map()
   
    for (let i = 0; i < n; i++) {
        let j = 0
        let size = 0
        if (seen.has(nums[i])) continue

        while (j < n) {
            if (nums[i] === nums[j]) {
                size++
            }
            j++
        }
        seen.set(nums[i],size)

    }
     let sorted = [...seen.entries()].sort((a, b) => b[1] - a[1])

    return sorted.slice(0, k).map(entry => entry[0])
};
scrnli_63DXhM1f0U1xL1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment