</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Merge k Sorted Lists

Core idea: Merging two sorted lists is easy and costs only their combined length. So don't merge the k lists one-by-one into a growing accumulator โ€” pair them up and merge pairs, halving the number of lists every round. After log k rounds you're down to one list, and each element rode through only log k merges instead of k.


Problem, rephrased

Forget the textbook phrasing. Here's the scenario:

You run a logging pipeline. k machines each emit a stream of events already sorted by timestamp โ€” within one machine, events come out in order, but the machines are independent. You want a single global timeline: one sorted sequence containing every event from all machines, still in timestamp order.

Each machine's stream is a sorted singly-linked list of timestamps. You're handed an array lists of their head pointers and must return the head of one merged sorted list. Let N be the total number of nodes across all k lists.

Input lists Output (merged) Why
[[1,4,5], [1,3,4], [2,6]] [1,1,2,3,4,4,5,6] classic interleave of three sorted lists
[] [] (None) zero lists โ†’ nothing to merge
[[]] [] (None) one list, and it's empty

The lists arrive as linked lists, not arrays โ€” so "look at the next smallest element" means following .next pointers, and we build the result by splicing nodes, not by copying values.


Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.