← Questions
Merge two sorted linked lists
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's CodeSignal assessment and at Google, last asked Jul 2025. It tests linked lists.
Given the heads of two singly linked lists, each sorted in non-decreasing order, merge them into one sorted list and return its head. Reuse the existing nodes; don't allocate new list nodes.
Interface
Unless you agree on a different interface with the interviewer, assume:
class ListNode: val: int; next: ListNode | None-
merge_two_lists(a: ListNode | None, b: ListNode | None) -> ListNode | None— when values are equal, take the node fromafirst so the merge is stable.
Example
merge_two_lists(1 -> 2 -> 4, 1 -> 3 -> 4) -> 1 -> 1 -> 2 -> 3 -> 4 -> 4
merge_two_lists(None, 0) -> 0
merge_two_lists(None, None) -> None
merge_two_lists(5, 1 -> 2 -> 3) -> 1 -> 2 -> 3 -> 5
Constraints
- Each list has up to 10^5 nodes; values fit in 32 bits.
Clarifying questions
- Are both lists sorted the same way (ascending)?
- May I modify the input nodes?
- Should equal values keep the order of their lists?
- Can either list be empty?
What a strong answer covers
- A dummy head and a tail pointer; repeatedly attach the smaller current node and advance; when one list runs out, attach the rest of the other in one step.
- O(m + n) time, O(1) extra space.
- The recursive version (
a.next = merge(a.next, b)whenais smaller) and why its O(m + n) stack depth is a risk for long lists. - Edge cases: empty lists, all of one list smaller than the other, duplicates.
Follow-ups
- Merge
ksorted lists: a min-heap of thekheads, O(N log k), or pairwise merging in rounds. - The lists are sorted in descending order, or in different orders.
- Remove duplicates while merging.
Where it's asked
- Meta · CodeSignal assessment · Last asked Jul 202590 min · Four levels on one class: basic operations, a ranking query, timestamps and expiry, then merge or snapshot and restore · No AI
- Google · First round: coding · Last asked Mar 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
linked lists
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding

