0
0
DSA Goprogramming~10 mins

Top K Frequent Elements Using Heap in DSA Go - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a map to count frequencies of elements.

DSA Go
freqMap := make(map[int][1])
Drag options to blanks, or click blank then click option'
Aint
Bstring
Cfloat64
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using string or bool as map value type instead of int.
Forgetting to initialize the map.
2fill in blank
medium

Complete the code to push an element with its frequency into the heap.

DSA Go
heap.Push(&h, [1]{num: num, freq: freqMap[num]})
Drag options to blanks, or click blank then click option'
Aelement
Bpair
Cnode
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect struct names like element or node.
Not passing the address of the heap.
3fill in blank
hard

Fix the error in the heap comparison function to create a max-heap by frequency.

DSA Go
func (h pairHeap) Less(i, j int) bool {
    return h[i].freq [1] h[j].freq
}
Drag options to blanks, or click blank then click option'
A<
B!=
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' creates a min-heap, which is incorrect here.
Using '==' or '!=' does not order elements properly.
4fill in blank
hard

Fill both blanks to pop the top element from the heap and append its number to the result slice.

DSA Go
top := heap.[1](&h).([2])
result = append(result, top.num)
Drag options to blanks, or click blank then click option'
APop
BPush
Cpair
DRemove
Attempts:
3 left
💡 Hint
Common Mistakes
Using Push instead of Pop.
Not type asserting the popped value.
5fill in blank
hard

Fill all three blanks to build the frequency map, push all pairs into the heap, and initialize the heap.

DSA Go
freqMap := make(map[int]int)
for _, num := range nums {
    freqMap[num] = freqMap[num] [1] 1
}
h := pairHeap{}
for num := range freqMap {
    heap.[2](&h, pair{num: num, freq: freqMap[num]})
}
heap.[3](&h)
Drag options to blanks, or click blank then click option'
A+=
BPush
CInit
D-=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' instead of '+=' for counting.
Forgetting to call heap.Init before popping.
Using wrong heap functions.