← Deloitte bank

Deloitte · Question 58 · Heaps

Merge k Sorted Lists

HeapsJavacode⏱ O(N log k)💾 O(k)
Service-based

Problem

Merge k sorted linked lists using a min-heap on current heads.

Approach

Push heads; pop smallest, append it, push its successor.

Time O(N log k)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:
lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
Output:
[1, 1, 2, 3, 4, 4, 5, 6]

Constraints

0 <= k <= 10^4; 0 <= total nodes <= 10^4.

Solution — read it, then walk it

Time O(N log k)Space O(k)Loops 4Branches 2Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class ListNodeDEFINE valListNode nextListNode(int v) { val = v;}DEFINE ListNodebuildList(int[] values)ListNode dummy = newListNode(0), tail = dummyfor (int v : values) {tail.next = newListNode(v); tail …RETURN dummy.nextDEFINE StringtoList(ListNode head)StringBuilder sb = newStringBuilder("[")while (head != null) {sb.append(head.val);head = head.next; i…RETURNsb.append("]").toString()DEFINE static ListNodemergeKLists(ListNode[]lists)PriorityQueue<ListNode> pq= new PriorityQueue<>((a,b) -> a.val - b.val)for (ListNode l :lists)if (l != null)pq.offer(l)ListNode dummy = newListNode(0), tail = dummywhile (!pq.isEmpty())ListNode n = pq.poll()tail.next = ntail = nif (n.next != null)pq.offer(n.next)RETURN dummy.nextDEFINE static voidmain(String[] args)ListNode[] lists ={buildList(new int[]{1, 4,5}), buildList(new int[]{1…System.out.println(toList(mergeKLists(lists)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/29

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