Bird
Raised Fist0
DSA Goprogramming~20 mins

Merge K Sorted Lists Using Min Heap in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Min Heap Merge Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of merging 3 sorted lists using min heap
What is the printed merged list after running the following Go code that merges 3 sorted linked lists using a min heap?
DSA Go
package main

import (
	"container/heap"
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

type MinHeap []*ListNode

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].Val < h[j].Val }
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.(*ListNode))
}

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

func mergeKLists(lists []*ListNode) *ListNode {
	h := &MinHeap{}
	heap.Init(h)

	for _, node := range lists {
		if node != nil {
			heap.Push(h, node)
		}
	}

	dummy := &ListNode{}
	current := dummy

	for h.Len() > 0 {
		minNode := heap.Pop(h).(*ListNode)
		current.Next = minNode
		current = current.Next
		if minNode.Next != nil {
			heap.Push(h, minNode.Next)
		}
	}

	return dummy.Next
}

func printList(head *ListNode) {
	for head != nil {
		fmt.Printf("%d -> ", head.Val)
		head = head.Next
	}
	fmt.Println("null")
}

func main() {
	list1 := &ListNode{1, &ListNode{4, &ListNode{5, nil}}}
	list2 := &ListNode{1, &ListNode{3, &ListNode{4, nil}}}
	list3 := &ListNode{2, &ListNode{6, nil}}

	merged := mergeKLists([]*ListNode{list1, list2, list3})
	printList(merged)
}
A1 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
B1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
C1 -> 1 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
D1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
Attempts:
2 left
💡 Hint
Remember the min heap always pops the smallest current node from all lists.
🧠 Conceptual
intermediate
1:30remaining
Understanding the role of the min heap in merging K sorted lists
Why is a min heap used to merge K sorted linked lists efficiently?
ABecause it merges lists by concatenating them directly
BBecause it sorts all elements at once in O(N log N) time
CBecause it stores all elements in a balanced binary search tree
DBecause it always provides the smallest current element among all lists in O(log K) time
Attempts:
2 left
💡 Hint
Think about how to get the smallest element quickly from multiple sorted lists.
🔧 Debug
advanced
1:30remaining
Identify the error in this min heap implementation for merging lists
What error will occur when running this Go code snippet for merging K sorted lists using a min heap?
DSA Go
type MinHeap []*ListNode

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].Val > h[j].Val }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
AThe merged list will be sorted in descending order, not ascending
BCompilation error due to incorrect method signatures
CRuntime panic due to nil pointer dereference
DThe heap will not compile because Less method returns bool incorrectly
Attempts:
2 left
💡 Hint
Check the Less method logic and how it affects heap order.
🚀 Application
advanced
1:00remaining
How many nodes are in the merged list after merging these K sorted lists?
Given 4 sorted linked lists with lengths 3, 2, 4, and 1 respectively, how many nodes will the merged list contain after merging using a min heap?
A10
B9
C8
D11
Attempts:
2 left
💡 Hint
Add the lengths of all lists to find total nodes.
❓ Predict Output
expert
2:00remaining
Output of merging empty and non-empty lists using min heap
What is the output of the following Go code that merges 3 lists where one is empty and others have nodes?
DSA Go
package main

import (
	"container/heap"
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

type MinHeap []*ListNode

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].Val < h[j].Val }
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.(*ListNode))
}

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

func mergeKLists(lists []*ListNode) *ListNode {
	h := &MinHeap{}
	heap.Init(h)

	for _, node := range lists {
		if node != nil {
			heap.Push(h, node)
		}
	}

	dummy := &ListNode{}
	current := dummy

	for h.Len() > 0 {
		minNode := heap.Pop(h).(*ListNode)
		current.Next = minNode
		current = current.Next
		if minNode.Next != nil {
			heap.Push(h, minNode.Next)
		}
	}

	return dummy.Next
}

func printList(head *ListNode) {
	for head != nil {
		fmt.Printf("%d -> ", head.Val)
		head = head.Next
	}
	fmt.Println("null")
}

func main() {
	list1 := (*ListNode)(nil)
	list2 := &ListNode{0, &ListNode{2, nil}}
	list3 := &ListNode{1, nil}

	merged := mergeKLists([]*ListNode{list1, list2, list3})
	printList(merged)
}
A0 -> 2 -> 1 -> null
B1 -> 0 -> 2 -> null
C0 -> 1 -> 2 -> null
Dnull
Attempts:
2 left
💡 Hint
Check how nil lists are skipped and how min heap orders nodes.

Practice

(1/5)
1. What is the main advantage of using a min heap to merge K sorted lists?
easy
A. It uses extra memory to store all elements at once.
B. It sorts each list individually before merging.
C. It efficiently finds the smallest element among the heads of all lists.
D. It merges lists by concatenating them without sorting.

Solution

  1. Step 1: Understand the role of a min heap in merging

    A min heap keeps track of the smallest elements efficiently, allowing quick access to the smallest head among K lists.
  2. Step 2: Compare other options

    Options B, C, and D do not describe the min heap's role correctly. Sorting individually or concatenating without sorting does not merge sorted lists efficiently.
  3. Final Answer:

    It efficiently finds the smallest element among the heads of all lists. -> Option C
  4. Quick Check:

    Min heap = efficient smallest element access [OK]
Hint: Min heap always gives smallest element fast [OK]
Common Mistakes:
  • Thinking min heap sorts entire lists
  • Assuming min heap stores all elements at once
  • Confusing min heap with simple concatenation
2. Which Go data structure is best suited to implement a min heap for merging K sorted lists?
easy
A. map
B. linked list
C. array without heap functions
D. slice with container/heap package

Solution

  1. Step 1: Identify Go's min heap implementation

    Go uses slices combined with the container/heap package to implement min heaps efficiently.
  2. Step 2: Evaluate other options

    Maps and linked lists do not provide heap properties. Arrays without heap functions lack automatic heap behavior.
  3. Final Answer:

    slice with container/heap package -> Option D
  4. Quick Check:

    Go min heap = slice + container/heap [OK]
Hint: Use container/heap with slice for min heap in Go [OK]
Common Mistakes:
  • Using map which has no order
  • Using linked list which is slow for heap ops
  • Ignoring container/heap package
3. What is the output of merging these 3 sorted lists using a min heap?
list1 = [1, 4, 7]
list2 = [2, 5, 8]
list3 = [3, 6, 9]
medium
A. [1, 3, 5, 7, 9, 2, 4, 6, 8]
B. [1, 2, 3, 4, 5, 6, 7, 8, 9]
C. [9, 8, 7, 6, 5, 4, 3, 2, 1]
D. [1, 4, 7, 2, 5, 8, 3, 6, 9]

Solution

  1. Step 1: Understand merging with min heap

    The min heap picks the smallest head element from all lists repeatedly, producing a fully sorted merged list.
  2. Step 2: Merge given lists step-by-step

    Starting with heads: 1, 2, 3; pick 1, then 2, then 3, then 4, 5, 6, 7, 8, 9 in order.
  3. Final Answer:

    [1, 2, 3, 4, 5, 6, 7, 8, 9] -> Option B
  4. Quick Check:

    Merge sorted lists = sorted combined list [OK]
Hint: Min heap merges by always picking smallest next element [OK]
Common Mistakes:
  • Concatenating lists without sorting
  • Reversing order incorrectly
  • Mixing elements from different lists randomly
4. Given this Go snippet for merging K sorted lists, what is the bug?
func mergeKLists(lists [][]int) []int {
    var result []int
    h := &IntHeap{}
    heap.Init(h)
    for _, list := range lists {
        for _, val := range list {
            heap.Push(h, val)
        }
    }
    for h.Len() > 0 {
        result = append(result, heap.Pop(h).(int))
    }
    return result
}
medium
A. Pushing all elements at once loses the benefit of merging sorted lists.
B. Heap is not initialized before pushing elements.
C. Result slice is not declared properly.
D. Heap.Pop returns wrong type.

Solution

  1. Step 1: Analyze the merging approach

    The code pushes all elements from all lists into the heap at once, ignoring the sorted order advantage.
  2. Step 2: Understand the impact

    This approach works but is inefficient (O(N log N)) instead of O(N log K) by pushing only heads and updating heap dynamically.
  3. Final Answer:

    Pushing all elements at once loses the benefit of merging sorted lists. -> Option A
  4. Quick Check:

    Push all elements = inefficient merge [OK]
Hint: Push only heads, not all elements at once [OK]
Common Mistakes:
  • Ignoring heap.Init call
  • Misunderstanding result slice declaration
  • Incorrect type assertion on Pop
5. You have K sorted linked lists of varying lengths. How would you efficiently merge them using a min heap in Go to minimize time complexity?
hard
A. Push the first node of each list into the min heap, then repeatedly pop the smallest and push its next node.
B. Push all nodes from all lists into the min heap at once, then pop all to get merged list.
C. Concatenate all lists and sort the combined list after.
D. Use a max heap instead of a min heap for merging.

Solution

  1. Step 1: Use min heap with heads of each list

    Push only the first node of each list into the min heap to keep track of the smallest current element among lists.
  2. Step 2: Pop smallest and push next node

    Pop the smallest node, add it to the merged list, then push the next node from that list into the heap, repeating until all nodes are processed.
  3. Step 3: Time complexity advantage

    This approach runs in O(N log K) time, where N is total nodes and K is number of lists, which is efficient.
  4. Final Answer:

    Push the first node of each list into the min heap, then repeatedly pop the smallest and push its next node. -> Option A
  5. Quick Check:

    Push heads + pop/push next = efficient merge [OK]
Hint: Push heads only, then push next nodes dynamically [OK]
Common Mistakes:
  • Pushing all nodes at once causing inefficiency
  • Using max heap which gives largest element first
  • Sorting concatenated list which is slower
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