Home › Company-wise questions › Deloitte › Merge k Sorted Lists ← Deloitte bank
Deloitte · Question 58 · Heaps
Merge k Sorted Lists Heaps Java code ⏱ O(N log k) 💾 O(k)
Service-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Push every list head into a min-heap. 2 Pop 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 Flowchart Pseudocode
Time O(N log k)Space O(k)Loops 4Branches 2Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE class ListNode DEFINE val ListNode next ListNode(int v) { val = v; } DEFINE ListNode buildList(int[] values) ListNode dummy = new ListNode(0), tail = dummy for (int v : values) { tail.next = new ListNode(v); tail … RETURN dummy.next DEFINE String toList(ListNode head) StringBuilder sb = new StringBuilder("[") while (head != null) { sb.append(head.val); head = head.next; i… RETURN sb.append("]").toString() DEFINE static ListNode mergeKLists(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 = new ListNode(0), tail = dummy while (!pq.isEmpty()) ListNode n = pq.poll() tail.next = n tail = n if (n.next != null) pq.offer(n.next) RETURN dummy.next DEFINE static void main(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← Q57 · Topological Sort / Course Schedule (II) Q59 · Binary Search Tree Iterator → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →