find the kth largest key in a map in go

To find the kth largest key in a map in Go, one possible approach is to create a slice of keys from the map, sort it in descending order, and return the kth element. Another approach is to use a max heap of keys, remove the largest elements k times, and return the kth element. Here is an example implementation of both methods:

main.go
import (
	"container/heap"
	"sort"
)

// Approach 1: sort and return kth element
func findKthLargestKeyBySorting(m map[int]string, k int) int {
	if k <= 0 || k > len(m) {
		return 0 // invalid k value
	}
	keys := make([]int, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))
	return keys[k-1]
}

// Approach 2: use max heap and remove top k elements
func findKthLargestKeyByHeap(m map[int]string, k int) int {
	if k <= 0 || k > len(m) {
		return 0 // invalid k value
	}
	keys := make([]int, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	h := IntMaxHeap(keys)
	heap.Init(&h)
	for i := 1; i < k; i++ {
		heap.Pop(&h)
	}
	return heap.Pop(&h).(int)
}

// IntMaxHeap defines a max heap of int keys
type IntMaxHeap []int

func (h IntMaxHeap) Len() int           { return len(h) }
func (h IntMaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntMaxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntMaxHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *IntMaxHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}
1160 chars
54 lines

Note that both methods assume that the keys in the map are of type int, but you can modify the code to work with other types or use generics in Go 2.0 when it becomes available.

related categories

gistlibby LogSnag