Bird
Raised Fist0
DSA Goprogramming~20 mins

Heap Concept Structure and Properties in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Heap Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this min-heap insertion sequence?
Consider a min-heap initially empty. Insert the elements in this order: 10, 4, 15, 1. What is the heap array after all insertions?
DSA Go
package main

import (
	"fmt"
)

func main() {
	heap := []int{}

	insert := func(h []int, val int) []int {
		h = append(h, val)
		idx := len(h) - 1
		for idx > 0 {
			parent := (idx - 1) / 2
			if h[parent] <= h[idx] {
				break
			}
			h[parent], h[idx] = h[idx], h[parent]
			idx = parent
		}
		return h
	}

	heap = insert(heap, 10)
	heap = insert(heap, 4)
	heap = insert(heap, 15)
	heap = insert(heap, 1)

	fmt.Println(heap)
}
A[10 4 15 1]
B[1 4 15 10]
C[4 1 15 10]
D[1 10 15 4]
Attempts:
2 left
💡 Hint
Remember min-heap property: parent is always smaller or equal to children.
🧠 Conceptual
intermediate
1:00remaining
Which property must a max-heap always satisfy?
Choose the correct property that defines a max-heap structure.
AAll leaf nodes have the same value.
BEvery parent node is less than or equal to its children.
CEvery parent node is greater than or equal to its children.
DThe heap is always a complete binary tree but no ordering property.
Attempts:
2 left
💡 Hint
Think about the largest element position in a max-heap.
🔧 Debug
advanced
1:30remaining
What error occurs when this heapify function is called with an invalid index?
Given this Go heapify function snippet, what error will occur if called with an index outside the heap array bounds?
DSA Go
func heapify(arr []int, n int, i int) {
	largest := i
	left := 2*i + 1
	right := 2*i + 2

	if left < n && arr[left] > arr[largest] {
		largest = left
	}
	if right < n && arr[right] > arr[largest] {
		largest = right
	}
	if largest != i {
		arr[i], arr[largest] = arr[largest], arr[i]
		heapify(arr, n, largest)
	}
}
Aruntime error: index out of range
Bcompilation error: undefined function heapify
Cno error, function handles invalid index gracefully
Druntime error: stack overflow
Attempts:
2 left
💡 Hint
Check what happens if i >= n when accessing arr[i].
🚀 Application
advanced
1:00remaining
How many elements are in the heap after these operations?
Start with an empty max-heap. Insert 5, 3, 8, 1, then remove the root once. How many elements remain in the heap?
A2
B4
C5
D3
Attempts:
2 left
💡 Hint
Each insertion adds one element; removal deletes one element.
❓ Predict Output
expert
2:30remaining
What is the heap array after heap sort on [4, 10, 3, 5, 1]?
Given the array [4, 10, 3, 5, 1], after performing heap sort (using max-heap), what is the final sorted array?
DSA Go
package main

import "fmt"

func heapify(arr []int, n int, i int) {
	largest := i
	left := 2*i + 1
	right := 2*i + 2

	if left < n && arr[left] > arr[largest] {
		largest = left
	}
	if right < n && arr[right] > arr[largest] {
		largest = right
	}
	if largest != i {
		arr[i], arr[largest] = arr[largest], arr[i]
		heapify(arr, n, largest)
	}
}

func heapSort(arr []int) {
	n := len(arr)
	for i := n/2 - 1; i >= 0; i-- {
		heapify(arr, n, i)
	}
	for i := n - 1; i > 0; i-- {
		arr[0], arr[i] = arr[i], arr[0]
		heapify(arr, i, 0)
	}
}

func main() {
	arr := []int{4, 10, 3, 5, 1}
	heapSort(arr)
	fmt.Println(arr)
}
A[1 3 4 5 10]
B[10 5 4 3 1]
C[1 4 3 5 10]
D[3 1 4 5 10]
Attempts:
2 left
💡 Hint
Heap sort outputs a sorted array in ascending order.

Practice

(1/5)
1. What is the main property of a max-heap data structure?
easy
A. Every parent node is less than or equal to its children
B. Every parent node is greater than or equal to its children
C. All leaf nodes are at the same level
D. The tree is always a complete binary tree

Solution

  1. Step 1: Understand max-heap property

    A max-heap requires that each parent node is greater than or equal to its children nodes.
  2. Step 2: Compare options with max-heap definition

    Every parent node is greater than or equal to its children matches the max-heap property exactly. Every parent node is less than or equal to its children describes a min-heap. All leaf nodes are at the same level and D are about tree shape, not heap order.
  3. Final Answer:

    Every parent node is greater than or equal to its children -> Option B
  4. Quick Check:

    Max-heap property = parent ≥ children [OK]
Hint: Max-heap means parent ≥ children always [OK]
Common Mistakes:
  • Confusing max-heap with min-heap property
  • Thinking heap requires all leaves at same level
  • Mixing heap order with tree completeness
2. Which of the following is the correct way to declare a min-heap using Go's container/heap package?
easy
A. var h []int = make([]int, 0) // slice for heap
B. var h heap.Interface = []int{} // direct slice assignment
C. var h = heap.NewMinHeap() // built-in min heap constructor
D. var h heap.Interface = &IntHeap{} // IntHeap implements heap.Interface

Solution

  1. Step 1: Recall Go heap package usage

    Go's container/heap requires a type implementing heap.Interface, like IntHeap struct.
  2. Step 2: Analyze options for correct syntax

    var h heap.Interface = &IntHeap{} // IntHeap implements heap.Interface correctly declares a heap.Interface variable with a pointer to IntHeap. var h []int = make([]int, 0) // slice for heap is just a slice, not a heap. var h = heap.NewMinHeap() // built-in min heap constructor is invalid; no NewMinHeap exists. var h heap.Interface = []int{} // direct slice assignment assigns a slice directly to heap.Interface, which is invalid.
  3. Final Answer:

    var h heap.Interface = &IntHeap{} // IntHeap implements heap.Interface -> Option D
  4. Quick Check:

    Heap needs heap.Interface implementation [OK]
Hint: Heap in Go needs heap.Interface implementation [OK]
Common Mistakes:
  • Using slice directly without implementing heap.Interface
  • Assuming built-in heap constructors exist
  • Assigning slice to heap.Interface without pointer
3. Consider the following Go code using a max-heap implemented with container/heap:
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[0 : n-1]
    return x
}

func main() {
    h := &IntHeap{3, 1, 4}
    heap.Init(h)
    heap.Push(h, 2)
    max := heap.Pop(h)
    fmt.Println(max)
}
What is the printed output?
medium
A. 4
B. 3
C. 2
D. 1

Solution

  1. Step 1: Understand heap initialization and ordering

    The IntHeap Less method uses h[i] > h[j], so it is a max-heap. Initial elements are 3,1,4.
  2. Step 2: Trace heap operations

    After heap.Init, the heap orders elements as max-heap. Then 2 is pushed. The heap now contains 4,3,1,2. heap.Pop removes the max element, which is 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    Max-heap pop returns max = 4 [OK]
Hint: Max-heap pop returns largest element [OK]
Common Mistakes:
  • Confusing min-heap and max-heap Less function
  • Assuming heap.Pop returns smallest element
  • Not tracing heap.Init effect on order
4. The following Go code attempts to create a min-heap but has a bug:
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[0 : n-1]
    return x
}

func main() {
    h := &IntHeap{5, 3, 8}
    heap.Init(h)
    heap.Push(h, 1)
    min := heap.Pop(h)
    fmt.Println(min)
}
What is the bug and how to fix it?
medium
A. Less method uses > instead of <; change to h[i] < h[j]
B. Push method should use pointer receiver; change to (h IntHeap)
C. Pop method returns wrong element; should return old[0]
D. Heap must be initialized with make([]int, 0) instead of literal

Solution

  1. Step 1: Identify heap type from Less method

    The Less method uses h[i] > h[j], which creates a max-heap, not a min-heap.
  2. Step 2: Fix Less method for min-heap

    To make a min-heap, Less should return h[i] < h[j]. This fixes the ordering so smallest element is on top.
  3. Final Answer:

    Less method uses > instead of <; change to h[i] < h[j] -> Option A
  4. Quick Check:

    Min-heap requires Less = h[i] < h[j] [OK]
Hint: Min-heap Less returns h[i] < h[j] [OK]
Common Mistakes:
  • Confusing Less method direction for min vs max heap
  • Changing Push receiver incorrectly
  • Misunderstanding Pop return value
5. You have a list of integers: [7, 2, 5, 3, 9, 1]. You want to find the 3 largest elements efficiently using a min-heap of size 3. Which approach correctly uses heap properties to solve this?
hard
A. Sort the list and pick last 3 elements
B. Build a max-heap with all elements, then pop 3 times to get largest elements
C. Build a min-heap with first 3 elements, then for each remaining element, if greater than heap root, replace root and heapify
D. Build a min-heap with all elements and pop 3 times

Solution

  1. Step 1: Understand problem and heap size constraint

    We want top 3 largest elements efficiently, so keep a min-heap of size 3 to track current largest.
  2. Step 2: Use min-heap to track largest elements

    Build min-heap with first 3 elements. For each remaining element, if it is larger than heap root (smallest in heap), replace root and heapify. This keeps 3 largest elements in heap.
  3. Step 3: Analyze options

    Build a min-heap with first 3 elements, then for each remaining element, if greater than heap root, replace root and heapify matches this approach. Build a max-heap with all elements, then pop 3 times to get largest elements uses max-heap on all elements, which is less efficient. Sort the list and pick last 3 elements sorts entire list, which is more work. Build a min-heap with all elements and pop 3 times pops smallest elements, not largest.
  4. Final Answer:

    Build a min-heap with first 3 elements, then for each remaining element, if greater than heap root, replace root and heapify -> Option C
  5. Quick Check:

    Min-heap size 3 tracks top 3 largest [OK]
Hint: Use min-heap of size k to track k largest elements [OK]
Common Mistakes:
  • Using max-heap on all elements (less efficient)
  • Sorting entire list unnecessarily
  • Using min-heap on all elements and popping smallest
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard