You get the first nodes, list1 and list2, of two singly linked lists. Each list is already sorted from smallest to largest value, and either list may be empty.
Join them into a single sorted linked list by relinking the nodes you were given, not by making new ones, and return the first node of the result.
Example 1
Input: list1 = [2, 5, 7], list2 = [1, 5, 8, 9] Output: [1, 2, 5, 5, 7, 8, 9] Why: take the smaller front node each time
2 more examples and the constraints
Example 2
Input: list1 = [], list2 = [] Output: [] Why: nothing to merge
Example 3
Input: list1 = [4], list2 = [] Output: [4] Why: one list is empty, so the other is the answer
Constraints
- 0 ≤ nodes in each list ≤ 50
- −100 ≤ node value ≤ 100
- Each list is in non-decreasing order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy, sort, rebuildO((n+m) log(n+m))
- RecursionO(n+m)
- Dummy head, iterativeO(n+m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two lists of 50 nodes | Verdict |
|---|---|---|---|
| Copy, sort, rebuild | O((n+m) log(n+m)) | Works; ignores the sorted input | |
| Recursion | O(n+m) | Passes; stack grows with the lists | |
| Dummy head, iterative | O(n+m) | Best; constant extra memory |
n and m = number of nodes in list1 and list2.
Edge cases to test
- Both lists empty. Return null, which the tests show as [].
- One list empty. [4] and [] must give [4]; the leftover attach handles it with no loop rounds.
- Equal values. [3, 3, 3] and [3, 3] must keep all five nodes.
- One list entirely smaller. [1, 2, 3] and [4, 5, 6]: the loop ends early and the whole second list is attached.
Common mistakes
- Forgetting to attach the leftover list after the loop, which drops the largest values.
- Returning
dummyinstead ofdummy.next, so the answer starts with a fake 0. - Moving
tailbefore linking the node, or forgetting to move it at all, which overwrites links.
How to talk through it
- 1Clarify. Can a list be empty? Should I reuse the nodes or may I make new ones? Can values repeat?
- 2Give the simple answer. Copy, sort, rebuild works; say it wastes the fact that both lists are sorted.
- 3Name the merge. This is merge sort's merge step: the smaller front node always comes next.
- 4Code it with a dummy. Explain that the dummy removes the special case for the first node and that the leftover list is attached in one move.
- 5Test out loud. Run both-empty, one-empty and equal-values cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?