Quick revision
The short answer
Merging k sorted linked lists is a heaps and top k problem, because each step must take the smallest of k current heads. We keep the head of every list in a min-heap, repeatedly poll the smallest node onto the result and push its successor from the same list. Each of the N nodes passes once through a heap of at most k nodes, so it takes O(N log k) time and O(k) extra space.
The solution
What it costs
| Approach | Time | Extra space | Uses the sorted order? |
|---|---|---|---|
| Gather all values and sort | O(N log N) | O(N) | no |
| Merge lists one after another | O(N k) | O(1) | yes, but rewalks the result |
| Merge in pairs, round by round | O(N log k) | O(1) | yes |
| Min-heap of current heads | O(N log k) | O(k) | yes |
What to remember
We merged k sorted lists by keeping only their current heads in a min-heap. Each step polls the smallest head, attaches it to the result behind a dummy node, and pushes its successor, so the heap always holds one candidate per unfinished list. It takes O(N log k) time and O(k) space and reuses the original nodes. The clue to remember is a choice of the smallest among several candidates that repeats as the candidates change: keep the candidates in a heap.
1What it means to merge several sorted lists into one
Imagine three piles of exam papers on a desk. Each pile is already in order of roll number, with the smallest number on top, and you must make one big pile in order. You would not shuffle everything and sort it again. You would look at the three top sheets, take the one with the smallest number, put it face down on your new pile, and look again. Only the top sheets matter, because whatever lies underneath a top sheet is larger than it. This article is that habit, written in Java.
In the problem the piles are linked lists. A linked list is a chain of nodes, where each node holds a value and a reference called next to the node after it, and the first node is the head. We are given k such lists, each sorted from small to large, and must return one sorted list that contains every node. We write N for the total number of nodes and k for the number of lists.
Let us keep one example, in which L1 is 1 -> 4 -> 5, L2 is 1 -> 3 -> 4 and L3 is 2 -> 6, so k is 3 and N is 8. Do it by hand with the three heads 1, 1 and 2. Take a 1, say from L1, and L1's top becomes 4. The heads are now 4, 1 and 2, so take the 1 from L2; its top becomes 3. Then 2 from L3, then 3, then a 4, the other 4, 5 and 6. The answer is 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6.
Each row is one sorted linked list. The merged answer, shown beside them, reuses these same eight nodes.
- L1
- 1 -> 4 -> 5
- L2
- 1 -> 3 -> 4
- L3
- 2 -> 6
- expected
- 1 1 2 3 4 4 5 6
1We are given three sorted lists, L1, L2 and L3. The heads 1, 1 and 2 are the smallest node of each list, and the answer must be all eight nodes in order.
What to assume
- Can a list be empty, or can there be no lists at all?
- Yes, and an empty input gives an empty result.
- Can values repeat or be negative?
- Yes.
- Should we make new nodes or reuse the ones we were given?
- We reuse them by changing their next references, which interviewers usually expect.
Notice how small each decision was. We never compared more than three numbers, one per list, however long the lists were. That is the reassuring thing about this problem: it looks like a big sorting job, but each step is a choice among k candidates, and the only real question is how to make that choice quickly.
A careful candidate asks a few questions first. Can a list be empty, or can there be no lists at all? Yes, and an empty input gives an empty result. Can values repeat or be negative? Yes. Should we make new nodes or reuse the ones we were given? We reuse them by changing their next references, which interviewers usually expect.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to spot the heap pattern in the question
A beginner reading this question usually thinks of sorting, because the word sorted appears twice. That is a sensible first thought, and we will try it. Others remember merging two sorted lists, a classic exercise, and wonder how to stretch it to k lists. Both ideas work. To find the better one, let us read the question slowly and take its clues one at a time.
The first clue is that each list is already sorted. That means the smallest node left in any list is always its head. So at every moment the next node of the answer is one of only k nodes, the current heads, which is exactly what the desk of exam papers showed us.
The second clue is that this choice repeats. We pick the smallest head, and then a new node, the successor of the one we took, becomes a head in its place. So we need a container that keeps a changing set of k items and hands us the smallest one, again and again, cheaply. Looking through all k heads every time would cost k steps per node.
Together these clues point to the heaps and top k family. A heap is a container that always knows its smallest item, the way a glance at the top sheets showed us the smallest paper. In Java the PriorityQueue class is such a heap, called a min-heap because the minimum comes out first. We will look inside it later; for now it is enough to know that adding an item or removing the smallest costs about log2 k steps when it holds k items, which we write O(log k).
The general rule to carry to new problems is this. When you must repeatedly take the smallest or largest of a set that changes after every take, keep the set in a heap. Merging k sorted things, finding the k closest points and scheduling the next event all have this shape.
Two neighbours look similar. Merging two sorted lists is a two pointer problem, one finger on each list, and it is the building block of a real alternative, merging the lists in pairs, which we cover in the questions at the end. Sorting all the values fits too, but it throws away the fact that each list is already sorted.
3The honest first attempt, a brute force that gathers every value and sorts
The first solution most people write is a brute force that ignores the lists' order. Walk every list and copy each value into an ArrayList, sort it, and build a new list from the sorted values. It is short and correct, and in an interview it is a fine thing to say first, because it gives you a working answer to improve.
On our example we copy the eight values 1, 4, 5, 1, 3, 4, 2 and 6, sort them into 1, 1, 2, 3, 4, 4, 5, 6, and make eight new nodes. Sorting N values with a general sort costs about N times log2 N comparisons, so the time is O(N log N). The space is O(N) for the copied values and the new nodes. It also copies when we wanted to relink.
There is a middle step that does use the sorted order. Merge L1 with L2 using the two-list merge, then merge that result with L3, and so on. The trouble is that the growing result is walked again in every merge. With k lists of about N / k nodes each, the merges walk 2N / k, then 3N / k, and so on up to N nodes, which adds up to about N times k / 2 steps, so O(N k). With 1,000 lists that is very slow.
So where is the waste? The sort compares numbers that were already in order inside each list, and the one-by-one merge walks the same early nodes many times. In both cases we redo work whose answer we already had. What we really need at each step is only the smallest of the k current heads, and the question that leads further is how to keep those k heads so the smallest can be found without looking at all of them.
4Getting to the heap solution, one observation at a time
The first observation comes straight from the exam papers. The next node of the merged list is always the smallest of the k current heads, because each list is sorted and its head is its smallest remaining node. So we never need to look deeper than the heads.
The second observation is about how the heads change. When we take a head, only one list changes, and its new head is the successor of the node we took. So the set of candidates changes by exactly one item out and at most one item in. A heap handles that well: we remove the smallest with poll and add the successor with add, each costing O(log k).
Why log k? Inside, the PriorityQueue keeps its items in an array that it treats like a family tree: the item at the top, called the root, has two children below it, each of those has two children, and so on. The one promise is that a parent is never larger than its children, so the smallest item is always at the root. Removing the root or adding an item only moves one item up or down this tree, one level at a time, and a tree holding k items has about log2 k levels. The small picture shows the first poll and add on our example.
Now we can write the method in words. Put the head of every non-empty list into a PriorityQueue ordered by value. While the heap is not empty, poll the smallest node, attach it to the end of the result, and if that node has a next, add the next to the heap. When the heap is empty, every node has been attached.
The PriorityQueue's own array drawn as a tree. Each label is a value and the list it came from, so 1:L2 is the 1 from L2.
- heap array
- 1:L1 1:L2 2:L3
1After adding the three heads, the smallest value sits at the root. Each parent is no larger than its children, which is all a heap promises.
- heap array
- 1:L2 2:L3
- polled
- 1:L1
2poll removes the root, 1:L1. The heap moves its last item, 2:L3, to the top, sees that its child 1:L2 is smaller, and swaps the two.
- heap array
- 1:L2 2:L3 4:L1
- added
- 4:L1
3add puts 4:L1, the successor of the polled node, in the next free place. It is not smaller than its parent, so it stays there.
Here is the question a beginner asks at this point. Why not put all N nodes into the heap at the start and poll them one by one? Let us try it and see what we lose. It works, but the heap then holds N nodes, so each operation costs O(log N) and the heap needs O(N) space; it is really the sorting attempt in disguise. Keeping only one node per list is what makes the heap small, and it is safe, because a node deeper in a list can never be smaller than its own list's head.
To build the result we use a small trick called a dummy node, a spare node placed in front of the answer so that attaching the first real node needs no special case. A second reference, tail, always points at the last node of the result, so attaching is tail.next = node followed by tail = node. At the end the answer starts at dummy.next.
Why is this correct? Every node enters the heap exactly once, either as a starting head or as the successor of a polled node, and leaves it exactly once, so every node is placed. Each poll returns the smallest of all remaining nodes, since every remaining node is either in the heap or behind a heap node of its own list, so the result comes out in sorted order. A mistake beginners often make is to forget to push the successor, which silently drops the rest of that list. Another is to write the comparator as a.val - b.val, which can overflow when the values have opposite signs near the int limits; Comparator.comparingInt avoids that.
5Watching the heap merge the three lists
The picture plays the method on our three lists. The nodes shown as being compared are the ones sitting in the heap at that moment; the node just polled is marked under the label poll; nodes already placed in the result are marked as done. The panel shows the heap's contents in order and the result so far.
Watch the size of the heap. However many nodes we place, it never holds more than one node from each list, so never more than three.
Compared nodes are in the heap, the poll label marks the node just taken, and done nodes are already in the result.
- heap
- 1(L1) 1(L2) 2(L3)
- result
- empty
1The heap starts with the head of every list: 1 from L1, 1 from L2 and 2 from L3. It holds only three nodes, one per list, never the whole input.
- polled
- 1 from L1
- pushed
- 4 from L1
- heap
- 1(L2) 2(L3) 4(L1)
- result
- 1
2We poll the smallest, the 1 from L1, and hang it on the result. Its successor in L1, the 4, takes its place in the heap, so L1 still has one candidate.
- polled
- 1 from L2
- pushed
- 3 from L2
- heap
- 2(L3) 3(L2) 4(L1)
- result
- 1 1
3The smallest is now the 1 from L2. We append it, and its successor 3 enters the heap. The result reads 1 1.
- polled
- 2 from L3
- pushed
- 6 from L3
- heap
- 3(L2) 4(L1) 6(L3)
- result
- 1 1 2
4Next comes the 2 from L3. We append it and push its successor 6. Notice that the heap still holds exactly one node from each list.
- polled
- 3 from L2
- pushed
- 4 from L2
- heap
- 4(L1) 4(L2) 6(L3)
- result
- 1 1 2 3
5The 3 from L2 is the smallest. We append it and push the next node of L2, its 4, so the heap now holds two 4s and the 6.
- polled
- 4 from L1
- pushed
- 5 from L1
- heap
- 4(L2) 5(L1) 6(L3)
- result
- 1 1 2 3 4
6Two 4s tie. The heap happened to hand us the 4 from L1 first, which is fine, since either order is sorted. L1's last node, 5, enters the heap.
- polled
- 4 from L2
- pushed
- nothing
- heap
- 5(L1) 6(L3)
- result
- 1 1 2 3 4 4
7We poll the 4 from L2. It was the last node of L2, so there is no successor to push, and the heap shrinks to two nodes.
- polled
- 5 from L1
- pushed
- nothing
- heap
- 6(L3)
- result
- 1 1 2 3 4 4 5
8We poll the 5 from L1, also the last of its list, so nothing is pushed. Only the 6 from L3 is left in the heap.
- polled
- 6 from L3
- pushed
- nothing
- heap
- empty
- result
- 1 1 2 3 4 4 5 6
9We poll the 6. The heap is empty, so every node has been placed, and the result is 1 1 2 3 4 4 5 6, built from the original nodes.
Let us read some frames back. In the second frame we take the 1 from L1, and its successor 4 enters the heap at once, so L1 keeps exactly one candidate. In the sixth frame the two 4s tie. PriorityQueue does not promise which equal item comes out first, and here it gave us L1's 4; either order gives a sorted result, so we do not care.
In the seventh and eighth frames the polled nodes are the last of their lists, so nothing is pushed and the heap shrinks from three to two to one. That is how finished lists simply stop taking part, with no special code. In the last frame the heap is empty and the result reads 1 1 2 3 4 4 5 6.
6The complete Java program
Here is the full program, with a small Node class, the mergeK method, and two helpers: of builds a list from values and show prints one. main merges our example, an empty input, a list of lists containing a null, and lists with negative values, and the comment on each line shows what it prints.
Let us read mergeK in the order it runs. First we create the PriorityQueue with Comparator.comparingInt(n -> n.val), which tells it to order nodes by their values. The first loop adds the head of every list, skipping a null head, because an empty list has no candidate to offer.
Next we make the dummy node and set tail to it. The while loop runs as long as the heap holds a candidate. Each time round, heap.poll() removes and returns the smallest head. tail.next = smallest attaches it, reusing the node rather than copying its value, and tail = smallest moves tail onto it. If smallest.next is not null, that successor is the new head of the same list, so we add it to the heap.
After the loop, tail.next = null is a safety line. The last node polled always has no successor, or its successor would still be in the heap, so its next is already null, but the line makes the ending obvious to a reader. Finally we return dummy.next, the first real node.
So the program prints [1 1 2 3 4 4 5 6] for the example, [] for no lists, [1] when a null list sits beside a real one, and [-5 -3 0 10 20] for the negative values.
7How much it costs, and the cases at the edges
Let us count on the example first. There were 8 polls and 8 adds, 3 for the starting heads and 5 for successors, so 16 heap operations. The heap never held more than 3 nodes, and a heap of 3 has two levels, so each operation moved a node at most one level. For N nodes and k lists each node is added once and polled once, each costing O(log k), so the time is O(N log k). With a million nodes in 1,000 lists, log2 k is about 10, against about 20 for log2 N in the sorting attempt.
The extra space is the heap, which holds at most k nodes, so it is O(k). The result reuses the input nodes, so it costs nothing extra.
| Approach | Time | Extra space | Uses the sorted order? |
|---|---|---|---|
| Gather all values and sort | O(N log N) | O(N) | no |
| Merge lists one after another | O(N k) | O(1) | yes, but rewalks the result |
| Merge in pairs, round by round | O(N log k) | O(1) | yes |
| Min-heap of current heads | O(N log k) | O(k) | yes |
The edge cases need no special code. No lists at all, or lists that are all empty, leave the heap empty, so the loop never runs and we return dummy.next, which is null. A null entry is skipped by the first loop. A single list comes back as it was. Very uneven lengths are handled naturally, because a finished list simply stops pushing successors.
8Follow-up questions
How does merging the lists in pairs reach the same O(N log k) bound?
Think of a knockout tournament. In the first round we merge list 0 with list 1, list 2 with list 3, and so on, using the ordinary two-list merge, which leaves about k / 2 lists. Then we repeat. Every round walks all N nodes once, and the number of lists halves each round, so there are about log2 k rounds, giving O(N log k). It needs no heap, and written as a loop it uses O(1) extra space, which some interviewers like to hear as a second answer.
What changes if the input is k sorted arrays instead of linked lists?
An array element has no next reference, so the heap stores a small record instead: the value, which array it came from and its position in that array. After polling a record, we push the element at the next position of the same array, if there is one. The time is still O(N log k), and the output is a new array of N values, because arrays cannot be relinked.
Why is the heap kept to k nodes rather than all N?
Because a node deeper in a list can never be the smallest while its own list's head is still waiting, so there is no point holding it yet. Keeping one node per list makes each heap operation O(log k) instead of O(log N) and the space O(k) instead of O(N).
9Conclusion
We merged k sorted lists by keeping only their current heads in a min-heap. Each step polls the smallest head, attaches it to the result behind a dummy node, and pushes its successor, so the heap always holds one candidate per unfinished list. It takes O(N log k) time and O(k) space and reuses the original nodes. The clue to remember is a choice of the smallest among several candidates that repeats as the candidates change: keep the candidates in a heap.
Open with
Let me confirm the setup. I have k sorted linked lists, some possibly empty or null, N nodes in total, and I return one sorted list that reuses the nodes.
Then, if they want more
Gathering every value and sorting works in O(N log N), but it ignores that each list is sorted, and merging the lists one after another is O(N k) because the growing result is rewalked. The key observation is that the next node of the answer is always the smallest of the k current heads.
So I keep those heads in a PriorityQueue ordered with Comparator.comparingInt on the value, skipping null lists.
Then, while the heap is not empty, I poll the smallest node, attach it behind a dummy node using a tail reference, and if it has a next, I add that next to the heap, because it is the new head of its list.
Every node enters and leaves the heap once, and the heap never holds more than k nodes, so the time is O(N log k) and the extra space is O(k). An empty input returns null. An alternative with the same time bound is merging the lists in pairs, round by round, which needs no heap.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 34 times in that collection. How it is counted
- Official documentation
- PriorityQueue (Java 21), Comparator (Java 21), Arrays (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Merge k sorted linked lists into a single sorted list.": https://scrivio-interview-library.netlify.app/data-structures/solutions/merge-k-sorted-linked-lists-into-a-single-sorted-list-d1e58c/