Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Merge K Sorted Lists Using Min Heap in DSA Javascript - 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 code that merges 3 sorted linked lists using a min heap?
DSA Javascript
class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

function mergeKLists(lists) {
  const minHeap = [];

  function heapPush(node) {
    minHeap.push(node);
    let i = minHeap.length - 1;
    while (i > 0) {
      let parent = Math.floor((i - 1) / 2);
      if (minHeap[parent].val <= minHeap[i].val) break;
      [minHeap[parent], minHeap[i]] = [minHeap[i], minHeap[parent]];
      i = parent;
    }
  }

  function heapPop() {
    const top = minHeap[0];
    const last = minHeap.pop();
    if (minHeap.length === 0) return top;
    minHeap[0] = last;
    let i = 0;
    while (true) {
      let left = 2 * i + 1;
      let right = 2 * i + 2;
      let smallest = i;
      if (left < minHeap.length && minHeap[left].val < minHeap[smallest].val) smallest = left;
      if (right < minHeap.length && minHeap[right].val < minHeap[smallest].val) smallest = right;
      if (smallest === i) break;
      [minHeap[i], minHeap[smallest]] = [minHeap[smallest], minHeap[i]];
      i = smallest;
    }
    return top;
  }

  for (const node of lists) {
    if (node) heapPush(node);
  }

  const dummy = new ListNode(0);
  let current = dummy;

  while (minHeap.length > 0) {
    let node = heapPop();
    current.next = node;
    current = current.next;
    if (node.next) heapPush(node.next);
  }

  return dummy.next;
}

// Lists:
// 1 -> 4 -> 5
// 1 -> 3 -> 4
// 2 -> 6

const l1 = new ListNode(1, new ListNode(4, new ListNode(5)));
const l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
const l3 = new ListNode(2, new ListNode(6));

const merged = mergeKLists([l1, l2, l3]);

let output = '';
let node = merged;
while (node) {
  output += node.val + ' -> ';
  node = node.next;
}
output += 'null';
console.log(output);
A1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
B1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
C1 -> 1 -> 3 -> 4 -> 4 -> 5 -> 6 -> null
D2 -> 6 -> 1 -> 3 -> 4 -> 4 -> 5 -> null
Attempts:
2 left
💡 Hint
Think about how the min heap always picks the smallest node among the heads of the lists.
🧠 Conceptual
intermediate
1:30remaining
Minimum number of elements in min heap during merge
During the process of merging k sorted lists using a min heap, what is the maximum number of elements that the min heap can contain at any time?
ASum of lengths of all lists, because all nodes are pushed at once
Bk, because the heap stores the current smallest nodes from each list
C1, because only one node is processed at a time
Dk squared, because nodes are pushed multiple times
Attempts:
2 left
💡 Hint
Consider how many nodes are pushed into the heap initially and during the process.
🔧 Debug
advanced
2:00remaining
Identify the error in min heap push operation
What error will occur when running this min heap push function used in merging k sorted lists?
DSA Javascript
function heapPush(node) {
  minHeap.push(node);
  let i = minHeap.length - 1;
  while (i > 0) {
    let parent = Math.floor(i / 2);
    if (minHeap[parent].val <= minHeap[i].val) break;
    [minHeap[parent], minHeap[i]] = [minHeap[i], minHeap[parent]];
    i = parent;
  }
}
ATypeError because minHeap is undefined
BNo error, function works correctly
CSyntaxError due to missing semicolon
DThe parent index calculation is wrong, causing incorrect heap structure
Attempts:
2 left
💡 Hint
Check how parent index is calculated in a binary heap stored in an array.
❓ Predict Output
advanced
2:00remaining
Output after merging empty and non-empty lists
What is the output of merging the following lists using the min heap merge function? Lists: - null - 0 -> 2 -> 5 - null
DSA Javascript
class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

function mergeKLists(lists) {
  const minHeap = [];

  function heapPush(node) {
    minHeap.push(node);
    let i = minHeap.length - 1;
    while (i > 0) {
      let parent = Math.floor((i - 1) / 2);
      if (minHeap[parent].val <= minHeap[i].val) break;
      [minHeap[parent], minHeap[i]] = [minHeap[i], minHeap[parent]];
      i = parent;
    }
  }

  function heapPop() {
    const top = minHeap[0];
    const last = minHeap.pop();
    if (minHeap.length === 0) return top;
    minHeap[0] = last;
    let i = 0;
    while (true) {
      let left = 2 * i + 1;
      let right = 2 * i + 2;
      let smallest = i;
      if (left < minHeap.length && minHeap[left].val < minHeap[smallest].val) smallest = left;
      if (right < minHeap.length && minHeap[right].val < minHeap[smallest].val) smallest = right;
      if (smallest === i) break;
      [minHeap[i], minHeap[smallest]] = [minHeap[smallest], minHeap[i]];
      i = smallest;
    }
    return top;
  }

  for (const node of lists) {
    if (node) heapPush(node);
  }

  const dummy = new ListNode(0);
  let current = dummy;

  while (minHeap.length > 0) {
    let node = heapPop();
    current.next = node;
    current = current.next;
    if (node.next) heapPush(node.next);
  }

  return dummy.next;
}

const l1 = null;
const l2 = new ListNode(0, new ListNode(2, new ListNode(5)));
const l3 = null;

const merged = mergeKLists([l1, l2, l3]);

let output = '';
let node = merged;
while (node) {
  output += node.val + ' -> ';
  node = node.next;
}
output += 'null';
console.log(output);
A0 -> 2 -> 5 -> null
Bnull
C0 -> null
D2 -> 5 -> null
Attempts:
2 left
💡 Hint
Only the non-null list contributes nodes to the merged list.
🧠 Conceptual
expert
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 nodes using a min heap?
AO(n k), because each node is compared with all k lists
BO(k log n), because heap operations depend on total nodes n
CO(n log k), because each node is pushed and popped from a heap of size k
DO(n + k), because heap operations are constant time
Attempts:
2 left
💡 Hint
Consider how many heap operations happen and the heap size.

Practice

(1/5)
1. What is the main purpose of using a min heap when merging K sorted lists?
easy
A. To sort each individual list before merging
B. To efficiently find the smallest element among the heads of all lists
C. To store all elements from all lists at once
D. To reverse the order of elements in each list

Solution

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

    A min heap helps quickly find the smallest element among multiple candidates, which is essential when merging sorted lists.
  2. Step 2: Apply this to merging K sorted lists

    By pushing the first element of each list into the min heap, we can always extract the smallest element efficiently to build the merged list.
  3. Final Answer:

    To efficiently find the smallest element among the heads of all lists -> Option B
  4. Quick Check:

    Min heap = smallest element finder [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 max heap
2. Which of the following is the correct way to insert an element into a min heap in JavaScript?
easy
A. heap.push(element); heapifyUp();
B. heap.pop(); heapifyDown();
C. heap.unshift(element); heapifyDown();
D. heap.shift(); heapifyUp();

Solution

  1. Step 1: Understand insertion in min heap

    To insert, add the element at the end (push), then move it up to maintain heap property (heapifyUp).
  2. Step 2: Match with options

    heap.push(element); heapifyUp(); correctly shows push followed by heapifyUp, which is the standard insertion method.
  3. Final Answer:

    heap.push(element); heapifyUp(); -> Option A
  4. Quick Check:

    Insert = push + heapifyUp [OK]
Hint: Insert by push then heapify up [OK]
Common Mistakes:
  • Using pop or shift to insert
  • Calling heapifyDown after insertion
  • Using unshift which is inefficient
3. What will be the output of the following code snippet that merges 3 sorted lists using a min heap?
const lists = [[1,4,5],[1,3,4],[2,6]];
function mergeKLists(lists) {
  const minHeap = [];
  const result = [];
  for (let i = 0; i < lists.length; i++) {
    if (lists[i].length > 0) minHeap.push({ val: lists[i][0], listIndex: i, elementIndex: 0 });
  }
  minHeap.sort((a,b) => a.val - b.val);
  while (minHeap.length > 0) {
    const smallest = minHeap.shift();
    result.push(smallest.val);
    const nextIndex = smallest.elementIndex + 1;
    if (nextIndex < lists[smallest.listIndex].length) {
      minHeap.push({ val: lists[smallest.listIndex][nextIndex], listIndex: smallest.listIndex, elementIndex: nextIndex });
      minHeap.sort((a,b) => a.val - b.val);
    }
  }
  return result;
}
console.log(mergeKLists(lists));
medium
A. [1,4,5,1,3,4,2,6]
B. [1,2,3,4,5,6]
C. [1,1,2,3,4,4,5,6]
D. [6,5,4,4,3,2,1,1]

Solution

  1. Step 1: Initialize min heap with first elements

    minHeap starts with {1,0,0}, {1,1,0}, {2,2,0} sorted as [1,1,2].
  2. Step 2: Extract smallest and add next elements

    Extract 1 from list 0, add 4; extract 1 from list 1, add 3; extract 2 from list 2, add 6; continue until all elements merged.
  3. Final Answer:

    [1,1,2,3,4,4,5,6] -> Option C
  4. Quick Check:

    Merged sorted list = [1,1,2,3,4,4,5,6] [OK]
Hint: Track smallest and add next from same list [OK]
Common Mistakes:
  • Not sorting minHeap after each insertion
  • Forgetting to add next element from same list
  • Returning concatenated lists instead of merged
4. Identify the bug in the following code snippet for merging K sorted lists using a min heap:
function mergeKLists(lists) {
  const minHeap = [];
  const result = [];
  for (let i = 0; i < lists.length; i++) {
    minHeap.push({ val: lists[i][0], listIndex: i, elementIndex: 0 });
  }
  minHeap.sort((a,b) => a.val - b.val);
  while (minHeap.length > 0) {
    const smallest = minHeap.shift();
    result.push(smallest.val);
    const nextIndex = smallest.elementIndex + 1;
    if (nextIndex < lists[smallest.listIndex].length) {
      minHeap.push({ val: lists[smallest.listIndex][nextIndex], listIndex: smallest.listIndex, elementIndex: nextIndex });
      minHeap.sort((a,b) => a.val - b.val);
    }
  }
  return result;
}
medium
A. Not initializing minHeap with first elements of lists
B. Not pushing the first element of each list into minHeap
C. Using shift() instead of pop() to get smallest element
D. Missing sorting minHeap after pushing new element inside the loop

Solution

  1. Step 1: Check minHeap maintenance inside loop

    After pushing a new element, minHeap must be sorted to keep smallest element at front.
  2. Step 2: Identify missing sorting

    The code pushes new elements but does not sort minHeap again, breaking the min heap property.
  3. Final Answer:

    Missing sorting minHeap after pushing new element inside the loop -> Option D
  4. Quick Check:

    Sort after push to maintain min heap [OK]
Hint: Always re-sort min heap after insertion [OK]
Common Mistakes:
  • Forgetting to sort minHeap after push
  • Confusing shift() and pop() usage
  • Not pushing initial elements into minHeap
5. Given K sorted linked lists, which approach best optimizes the time complexity when merging them using a min heap?
hard
A. Insert only the first element of each list into the min heap, then extract and insert next elements dynamically
B. Insert all elements from all lists into the min heap at once, then extract all
C. Merge lists two at a time without using a min heap
D. Concatenate all lists and sort the combined list

Solution

  1. Step 1: Analyze time complexity of inserting all elements at once

    Inserting all elements at once leads to O(N log N) where N is total elements, which is less efficient.
  2. Step 2: Understand dynamic insertion approach

    Inserting only first elements and dynamically adding next elements keeps heap size at K, leading to O(N log K) time, which is optimal.
  3. Final Answer:

    Insert only the first element of each list into the min heap, then extract and insert next elements dynamically -> Option A
  4. Quick Check:

    Dynamic insertion = O(N log K) best [OK]
Hint: Keep heap size small by dynamic insertion [OK]
Common Mistakes:
  • Inserting all elements at once causing slow performance
  • Ignoring heap size impact on complexity
  • Using simple concatenation and sort which is inefficient
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