3. Merge K Sorted Linked Lists

This problem was recently asked by Twitter: You are given an array of k sorted singly linked lists. Merge the linked lists into a single sorted linked list and return it.

class Node(object):
  def __init__(self, val, next=None):
    self.val = val
    self.next = next

  def __str__(self):
    c = self
    answer = ""
    while c:
      answer += str(c.val) if c.val else ""
      c = c.next
    return answer

def merge(lists):
  # Fill this in.

a = Node(1, Node(3, Node(5)))
b = Node(2, Node(4, Node(6)))
print merge([a, b])
# 123456

Lists 中有k個list, 每個長度假設為n

  • maintain a pointer for each linked list that indicates where we are in that list. Then each time, simply find the minimum value from all the pointers and add that to our output linked list, and advance that pointer

  • The most optimal solution involves the use of a minheap for the pointers

  • We simply grab the element at the top of the heap, and advance the corresponding pointer and add the new value to the heap.

Last updated