LeetCode Problem: Top K Frequent Elements
Problem statement:
Given an array of integers (numbers), you have to return the k most frequent elements
Example:
Input:
numbers: [1,2,3,4,5,6,1,2,1,2], k: 2
Expected output array:
[1,2]
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/top-k-frequent-elements/
Golang Solution:
import (
"fmt"
)
func topKFrequent(numbers []int, k int) []int {
arrayWithIndicesAsCount := make([]map[int]int, len(numbers)+1)
numbersCountMap := make(map[int]int, 0)
for _, num := range numbers {
if count, ok := numbersCountMap[num]; ok {
mapAtIndex := arrayWithIndicesAsCount[numbersCountMap[num]]
delete(mapAtIndex, num)
arrayWithIndicesAsCount[count] = mapAtIndex
numbersCountMap[num] += 1
mapAtIndexNew := arrayWithIndicesAsCount[numbersCountMap[num]]
if mapAtIndexNew == nil {
mapAtIndexNew = make(map[int]int)
}
mapAtIndexNew[num] = numbersCountMap[num]
arrayWithIndicesAsCount[numbersCountMap[num]] = mapAtIndexNew
} else {
numbersCountMap[num] = 1
arrayWithIndicesAsCountMap := arrayWithIndicesAsCount[numbersCountMap[num]]
if arrayWithIndicesAsCountMap == nil {
arrayWithIndicesAsCountMap = make(map[int]int)
}
arrayWithIndicesAsCountMap[num] = 1
arrayWithIndicesAsCount[1] = arrayWithIndicesAsCountMap
}
}
index := len(numbers)
result := make([]int, 0)
for index > 0 && k > 0 {
if arrayWithIndicesAsCount[index] != nil {
mapAtIndex := arrayWithIndicesAsCount[index]
for key, _ := range mapAtIndex {
result = append(result, key)
}
k -= len(mapAtIndex)
}
index -= 1
}
return result
}