K way merge Flashcards

(5 cards)

1
Q

What is K-way Merge?

A

K-way Merge merges k sorted lists using a min heap.

Use Case: Merge sorted arrays, external sorting.

Example: Merge K Sorted Lists.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps in K-way Merge?

A
  1. Initialize min heap with first elements.
  2. Pop smallest, add next from same list.
  3. Repeat until heap empty.

Action: Explain steps for Merge K Sorted Lists aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does K-way Merge apply to Merge K Sorted Lists?

A

The problem is to merge k sorted linked lists. The approach is to use a min heap to select the smallest node across lists.

Example: Merge K Sorted Lists.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas of K-way Merge?

A

Time complexity is O(n log k) and space complexity is O(k).
Gotchas include handling empty lists and single lists.

Action: List edge cases for Merge K Sorted Lists aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Code example for K-way Merge.

A

```python
from typing import List, Optional
from heapq import heappush, heappop
class ListNode:
def __init__(self, val: int = 0, next: ‘ListNode’ = None):
self.val = val
self.next = next
def merge_k_lists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
dummy = ListNode(0)
current = dummy
heap: List[tuple[int, ListNode]] = []
for i, node in enumerate(lists):
if node:
heappush(heap, (node.val, i, node))
while heap:
val, i, node = heappop(heap)
current.next = node
current = current.next
if node.next:
heappush(heap, (node.next.val, i, node.next))
return dummy.next
~~~

Action: Sketch heap merging on paper.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly