মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 6 · Heaps / Priority Queues

6.2 K-way Merge

চিনবেন কীভাবে
"merge k sorted lists/arrays", "smallest range covering k lists", "kth smallest in a sorted matrix" — a heap holds the current head of each list; pop the smallest, push its successor
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Merge k Sorted ListsLC 23 (Hard — Amazon/Meta/Google High)

Statement (Demo): Given an array of k sorted linked lists, merge them into one sorted linked list and return its head. Example: lists=[[1,4,5],[1,3,4],[2,6]][1,1,2,3,4,4,5,6] | ⚡ k ≤ 10⁴, total nodes ≤ 10⁴

Approach: Put the head of every non-empty list into a min-heap ordered by value. Pop the smallest node, attach it to the result (dummy node, see 3.2), and push that node's next. The heap never holds more than k nodes. (MinHeap → 6.1.)

function mergeKLists(lists) {
  const heap = new MinHeap((a, b) => a.val - b.val);
  for (const head of lists) if (head) heap.push(head);
  const dummy = { next: null };
  let tail = dummy;
  while (heap.size) {
    const node = heap.pop(); // smallest current head
    tail.next = node;
    tail = node;
    if (node.next) heap.push(node.next); // its successor joins the race
  }
  return dummy.next;
}

Complexity: Time O(N log k) for N total nodes, Space O(k) (divide-and-conquer pairwise merging is the heap-free alternative)

Demo · Merge k Sorted Listsplan · দিন ০৬৪LC 23
নোট · ফাঁকা

প্রবলেম

  • Kth Smallest Element in a Sorted Matrixplan · দিন ০৬৫🔥 Must-doLC 378
    (each row is a sorted list — k-way merge, or binary search on the value)

    Statement: Given an n × n matrix whose rows and columns are sorted ascending, return the k-th smallest element in sorted order.
    Example: matrix=[[1,5,9],[10,11,13],[12,13,15]], k=813 | ⚡ n ≤ 300

    নোট · ফাঁকা