Bird
Raised Fist0
DSA C++programming~20 mins

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

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Merge K Sorted Lists 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 C++ code that merges 3 sorted linked lists using a min heap?
DSA C++
#include <iostream>
#include <vector>
#include <queue>

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

struct compare {
    bool operator()(ListNode* a, ListNode* b) {
        return a->val > b->val;
    }
};

ListNode* mergeKLists(std::vector<ListNode*>& lists) {
    std::priority_queue<ListNode*, std::vector<ListNode*>, compare> minHeap;
    for (auto node : lists) {
        if (node) minHeap.push(node);
    }
    ListNode dummy(0);
    ListNode* tail = &dummy;
    while (!minHeap.empty()) {
        ListNode* top = minHeap.top();
        minHeap.pop();
        tail->next = top;
        tail = tail->next;
        if (top->next) minHeap.push(top->next);
    }
    return dummy.next;
}

int main() {
    ListNode a1(1), a2(4), a3(5);
    a1.next = &a2; a2.next = &a3;
    ListNode b1(1), b2(3), b3(4);
    b1.next = &b2; b2.next = &b3;
    ListNode c1(2), c2(6);
    c1.next = &c2;
    std::vector<ListNode*> lists = {&a1, &b1, &c1};
    ListNode* merged = mergeKLists(lists);
    while (merged) {
        std::cout << merged->val << " -> ";
        merged = merged->next;
    }
    std::cout << "null" << std::endl;
    return 0;
}
A1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
B1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
C1 -> 1 -> 3 -> 4 -> 5 -> 6 -> null
D1 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
Attempts:
2 left
💡 Hint
Trace the min heap operations and how nodes are popped and pushed.
🧠 Conceptual
intermediate
1:30remaining
Time complexity of merging K sorted lists using min heap
What is the time complexity of merging K sorted lists with a total of N elements using a min heap?
AO(K log N)
BO(N log K)
CO(N K)
DO(N log N)
Attempts:
2 left
💡 Hint
Consider how many times elements are pushed and popped from the heap and the heap size.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in min heap merge code
What runtime error will occur when running this code snippet that merges K sorted lists using a min heap?
DSA C++
#include <queue>
#include <vector>

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

struct compare {
    bool operator()(ListNode* a, ListNode* b) {
        return a->val < b->val; // Note: reversed comparison
    }
};

ListNode* mergeKLists(std::vector<ListNode*>& lists) {
    std::priority_queue<ListNode*, std::vector<ListNode*>, compare> minHeap;
    for (auto node : lists) {
        if (node) minHeap.push(node);
    }
    ListNode dummy(0);
    ListNode* tail = &dummy;
    while (!minHeap.empty()) {
        ListNode* top = minHeap.top();
        minHeap.pop();
        tail->next = top;
        tail = tail->next;
        if (top->next) minHeap.push(top->next);
    }
    return dummy.next;
}
AThe merged list will be sorted in descending order, not ascending
BCompilation error due to wrong comparator syntax
CInfinite loop because minHeap never empties
DSegmentation fault due to null pointer dereference
Attempts:
2 left
💡 Hint
Check the comparator logic and how it affects the priority queue ordering.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in min heap comparator
Which option contains the correct syntax for a comparator struct to use in a C++ priority_queue for merging K sorted lists?
Astruct compare { bool operator()(ListNode a, ListNode b) { return a.val > b.val; } };
Bstruct compare { bool operator(ListNode* a, ListNode* b) { return a->val > b->val; } };
Cstruct compare { bool operator()(ListNode* a, ListNode* b) { return a->val > b->val; } };
Dstruct compare { bool operator[](ListNode* a, ListNode* b) { return a->val > b->val; } };
Attempts:
2 left
💡 Hint
Look for the correct operator overloading syntax for function call operator.
🚀 Application
expert
1:00remaining
Number of nodes in merged list after merging K sorted lists
Given 4 sorted linked lists with lengths 3, 5, 2, and 4 respectively, how many nodes will the merged linked list contain after merging all using a min heap?
A9
B12
C10
D14
Attempts:
2 left
💡 Hint
Sum the lengths of all input lists.

Practice

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

Solution

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

    A min heap helps quickly find the smallest element among multiple sorted lists by always keeping the smallest element at the top.
  2. Step 2: Compare with other options

    Options A, B, and C do not describe the min heap's advantage correctly. The min heap does not sort lists individually or concatenate without sorting.
  3. Final Answer:

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

    Min heap = efficient smallest element retrieval [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 of the following is the correct way to push an element into a min heap in C++ using STL?
easy
A. std::priority_queue minHeap; minHeap.push(5);
B. std::priority_queue<int> minHeap; minHeap.push(5);
C. std::priority_queue minHeap; minHeap.push(5);
D. std::priority_queue minHeap; minHeap.push(5);

Solution

  1. Step 1: Identify min heap declaration syntax

    In C++, to create a min heap, use std::priority_queue with std::greater comparator and std::vector as container.
  2. Step 2: Check each option

    std::priority_queue minHeap; minHeap.push(5); uses std::greater and vector correctly. std::priority_queue<int> minHeap; minHeap.push(5); is max heap by default. std::priority_queue minHeap; minHeap.push(5); uses std::less which is max heap. std::priority_queue minHeap; minHeap.push(5); uses std::list which is invalid container for priority_queue.
  3. Final Answer:

    std::priority_queue minHeap; minHeap.push(5); -> Option C
  4. Quick Check:

    Min heap = priority_queue + greater + vector [OK]
Hint: Min heap needs std::greater and vector container [OK]
Common Mistakes:
  • Using default priority_queue (max heap)
  • Using std::less instead of std::greater
  • Using invalid container like std::list
3. What will be the output of the following code snippet that merges 3 sorted lists using a min heap?

#include <iostream>
#include <vector>
#include <queue>

struct Node {
    int val;
    int listIndex;
    int elementIndex;
    Node(int v, int li, int ei) : val(v), listIndex(li), elementIndex(ei) {}
};

struct Compare {
    bool operator()(Node const& a, Node const& b) {
        return a.val > b.val;
    }
};

int main() {
    std::vector lists = {{1,4,5}, {1,3,4}, {2,6}};
    std::priority_queue minHeap;

    for (int i = 0; i < lists.size(); i++) {
        if (!lists[i].empty())
            minHeap.push(Node(lists[i][0], i, 0));
    }

    std::vector<int> merged;
    while (!minHeap.empty()) {
        Node curr = minHeap.top();
        minHeap.pop();
        merged.push_back(curr.val);
        int nextIndex = curr.elementIndex + 1;
        if (nextIndex < lists[curr.listIndex].size()) {
            minHeap.push(Node(lists[curr.listIndex][nextIndex], curr.listIndex, nextIndex));
        }
    }

    for (int val : merged) std::cout << val << " ";
    return 0;
}
medium
A. 1 1 2 3 4 4 5 6
B. 1 2 3 4 4 5 6
C. 1 1 3 4 4 5 6 2
D. 2 1 1 3 4 4 5 6

Solution

  1. Step 1: Understand the merging process

    The code pushes the first element of each list into the min heap. Then it repeatedly extracts the smallest element and pushes the next element from the same list until all elements are merged.
  2. Step 2: Trace the merged output

    Lists: {1,4,5}, {1,3,4}, {2,6}. Merged order: 1 (from list0), 1 (list1), 2 (list2), 3 (list1), 4 (list0), 4 (list1), 5 (list0), 6 (list2).
  3. Final Answer:

    1 1 2 3 4 4 5 6 -> Option A
  4. Quick Check:

    Merge sorted lists = 1 1 2 3 4 4 5 6 [OK]
Hint: Push first elements, pop min, push next from same list [OK]
Common Mistakes:
  • Mixing order of elements
  • Forgetting to push next element after pop
  • Ignoring duplicates in merged output
4. Identify the bug in the following code snippet that attempts to merge K sorted lists using a min heap:

std::priority_queue minHeap;
for (auto& list : lists) {
    for (int val : list) {
        minHeap.push(val);
    }
}
std::vector<int> merged;
while (!minHeap.empty()) {
    merged.push_back(minHeap.top());
    minHeap.pop();
}
medium
A. The min heap is declared incorrectly and will cause a compilation error.
B. The code pushes all elements at once, losing the benefit of merging sorted lists efficiently.
C. The code does not pop elements from the min heap, causing an infinite loop.
D. The merged vector is not initialized before use.

Solution

  1. Step 1: Analyze the approach used

    The code pushes all elements from all lists into the min heap at once, then pops them to get sorted order.
  2. Step 2: Identify inefficiency

    This approach loses the efficiency of merging K sorted lists using min heap by only pushing the first element of each list and pushing next elements on demand.
  3. Final Answer:

    The code pushes all elements at once, losing the benefit of merging sorted lists efficiently. -> Option B
  4. Quick Check:

    Push all elements at once = inefficient merge [OK]
Hint: Push only first elements, then next after popping [OK]
Common Mistakes:
  • Pushing all elements at once
  • Ignoring heap declaration correctness
  • Forgetting to pop elements in loop
5. Given K sorted linked lists, how can you modify the min heap approach to merge them efficiently if some lists are empty and others have duplicate values?
hard
A. Ignore empty lists and merge only non-empty lists by concatenation without using a min heap.
B. Use a max heap instead of min heap to handle duplicates and empty lists.
C. Push all elements from all lists into the min heap at once, then pop to merge, skipping duplicates manually.
D. Initialize the min heap with the first non-empty element of each list and push next elements only when popping, allowing duplicates naturally.

Solution

  1. Step 1: Handle empty lists and duplicates

    Skip empty lists when initializing the min heap. For duplicates, min heap naturally handles them by ordering values.
  2. Step 2: Efficient merging strategy

    Push only the first element of each non-empty list into the min heap. When popping, push the next element from the same list if it exists. This keeps memory and operations efficient.
  3. Final Answer:

    Initialize the min heap with the first non-empty element of each list and push next elements only when popping, allowing duplicates naturally. -> Option D
  4. Quick Check:

    Push first non-empty elements, push next on pop, duplicates allowed [OK]
Hint: Skip empty lists, push next element after pop [OK]
Common Mistakes:
  • Pushing all elements at once wasting memory
  • Ignoring empty lists causing errors
  • Using max heap which breaks order
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