← Uber bank

Uber · Question 56 · Heaps

Merge k Sorted Lists

HeapsPythoncode⏱ O(Nlogk)💾 O(k)
Product-based

Problem

You are given an array of k linked lists, each sorted in ascending order. Merge all the lists into one sorted list and return it.

Approach

Use a min - heap (pr iority queue) to always pick the smallest current node across all lists.  Push the head of each list into the heap  Pop the smallest, append to result, and push its next (if exists)

Time O(Nlogk)Space O(k)

How it works

  1. 1Push every list head into a min-heap.
  2. 2Pop the smallest, append it, push its successor.

Sample input / output

Input:
3
3 1 4 5
3 1 3 4
2 2 6
Output:
[0, 1, 1, 2, 3, 4, 4, 5, 6]

Constraints

0 <= k <= 10^4; 0 <= nodes total <= 10^4; values sorted per list.

Solution — read it, then walk it

Time O(Nlogk)Space O(k)Loops 5Branches 3Returns 4source · Python
Scroll sideways for wide charts — the view follows the active step.
yes↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeat↻ repeat↻ repeatyesSTARTimport heapqDEFINE mergeKLists(lists)min_heap = []for ln in listsif lnheapq.heappush(min_heap,ln)dummy = ListNode(0)tail = dummywhile min_heapnode =heapq.heappop(min_heap)tail.next = nodetail = tail.nextif node.nextheapq.heappush(min_heap,node.next)RETURN dummyCLASS ListNodeDEFINE __init__(self,val=0, next=None)self.val = valself.next = nextDEFINE __lt__(self, other)RETURN self.val < other.valDEFINE build_list(values)dummy = tail = ListNode()for v in valuestail.next = ListNode(v)tail = tail.nextRETURN dummy.nextDEFINE to_list(head)out = []while headout.append(head.val)head = head.nextRETURN outDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)k = int(next(it))lists = []for _ in range(k)n = int(next(it))lists.append(build_list([int(next(it))for _ in range(n)]))print(to_list(mergeKLists(lists)))if __name__ =="__main__"main()
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits