0
0
DSA Goprogramming~20 mins

Top K Frequent Elements Using Heap in DSA Go - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Heap Mastery: Top K Frequent Elements
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Top K Frequent Elements with Min-Heap
What is the output of the following Go code that finds the top 2 frequent elements using a min-heap?
DSA Go
package main

import (
	"container/heap"
	"fmt"
)

type Element struct {
	value int
	freq  int
}

type MinHeap []Element

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].freq < h[j].freq }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(Element))
}

func (h *MinHeap) Pop() interface{} {
	n := len(*h)
	el := (*h)[n-1]
	*h = (*h)[:n-1]
	return el
}

func topKFrequent(nums []int, k int) []int {
	freqMap := make(map[int]int)
	for _, num := range nums {
		freqMap[num]++
	}

	h := &MinHeap{}
	heap.Init(h)

	for val, freq := range freqMap {
		heap.Push(h, Element{val, freq})
		if h.Len() > k {
			heap.Pop(h)
		}
	}

	res := make([]int, 0, k)
	for h.Len() > 0 {
		res = append(res, heap.Pop(h).(Element).value)
	}
	return res
}

func main() {
	nums := []int{1,1,1,2,2,3}
	k := 2
	result := topKFrequent(nums, k)
	fmt.Println(result)
}
A[1, 2]
B[2, 1]
C[3, 2]
D[1, 3]
Attempts:
2 left
💡 Hint
Remember that the min-heap pops the smallest frequency first, so the final slice is built by popping from smallest to largest frequency.
🧠 Conceptual
intermediate
1:30remaining
Understanding Heap Usage in Top K Frequent Elements
Why is a min-heap used instead of a max-heap to find the top k frequent elements efficiently?
ABecause a min-heap sorts elements in descending order automatically.
BBecause a min-heap stores elements in increasing order of their values, not frequency.
CBecause a max-heap cannot be implemented efficiently in Go.
DBecause a min-heap keeps the smallest frequency at the top, allowing easy removal of less frequent elements when size exceeds k.
Attempts:
2 left
💡 Hint
Think about how to maintain only the top k frequent elements while processing all frequencies.
🔧 Debug
advanced
2:00remaining
Identify the Error in Heap Implementation
What error will occur when running this Go code snippet that implements a min-heap for top k frequent elements?
DSA Go
type MinHeap []Element

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].freq > h[j].freq }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
AThe heap will behave as a max-heap, not a min-heap, causing incorrect top k results.
BSyntax error due to missing pointer receiver in methods.
CRuntime panic due to index out of range in Swap method.
DNo error; code works correctly as min-heap.
Attempts:
2 left
💡 Hint
Check the Less method logic carefully.
Predict Output
advanced
2:00remaining
Output of Top K Frequent Elements with Equal Frequencies
What is the output of this Go code when multiple elements have the same frequency?
DSA Go
package main

import (
	"container/heap"
	"fmt"
)

type Element struct {
	value int
	freq  int
}

type MinHeap []Element

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool {
	if h[i].freq == h[j].freq {
		return h[i].value > h[j].value
	}
	return h[i].freq < h[j].freq
}
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(Element))
}

func (h *MinHeap) Pop() interface{} {
	n := len(*h)
	el := (*h)[n-1]
	*h = (*h)[:n-1]
	return el
}

func topKFrequent(nums []int, k int) []int {
	freqMap := make(map[int]int)
	for _, num := range nums {
		freqMap[num]++
	}

	h := &MinHeap{}
	heap.Init(h)

	for val, freq := range freqMap {
		heap.Push(h, Element{val, freq})
		if h.Len() > k {
			heap.Pop(h)
		}
	}

	res := make([]int, 0, k)
	for h.Len() > 0 {
		res = append(res, heap.Pop(h).(Element).value)
	}
	return res
}

func main() {
	nums := []int{4,4,1,1,2,2,3}
	k := 3
	result := topKFrequent(nums, k)
	fmt.Println(result)
}
A[3, 4, 1]
B[1, 2, 3]
C[3, 2, 1]
D[4, 3, 2]
Attempts:
2 left
💡 Hint
When frequencies tie, the element with larger value is considered smaller in heap order.
🚀 Application
expert
2:30remaining
Optimizing Top K Frequent Elements for Large Data
You have a very large list of integers and want to find the top 5 frequent elements efficiently. Which approach is best to optimize memory and speed?
AUse a hash map to count frequencies, then a min-heap of size 5 to keep top elements while iterating over the map.
BSort the entire list and then count frequencies by scanning, finally pick top 5 elements.
CUse a max-heap containing all unique elements and pop top 5 elements after building it.
DUse a balanced binary search tree to store frequencies and extract top 5 elements.
Attempts:
2 left
💡 Hint
Consider both time and space complexity for large input.