Merge two sorted linked lists
Company: HubSpot
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of linked list manipulation, algorithmic reasoning for merging sorted sequences, and the ability to analyze time and space complexity while handling edge cases such as empty lists and duplicate values.
Constraints
- 0 <= len(list1), len(list2) <= 5000
- -10^4 <= node value <= 10^4
- Both list1 and list2 are sorted in non-decreasing order
Examples
Input: ([1, 2, 4], [1, 3, 4])
Expected Output: [1, 1, 2, 3, 4, 4]
Explanation: Standard interleave; the two equal 1s and two equal 4s are all preserved, with list1's value taken first on ties.
Input: ([], [])
Expected Output: []
Explanation: Both lists empty -> the merged list is empty.
Input: ([], [0])
Expected Output: [0]
Explanation: One list empty -> the result is just the other list.
Input: ([5], [])
Expected Output: [5]
Explanation: Symmetric empty-list case for the second list.
Input: ([1, 1, 1], [1, 1])
Expected Output: [1, 1, 1, 1, 1]
Explanation: All duplicate values across both lists are kept; total length is the sum of inputs.
Input: ([-5, -3, 0], [-4, -2, 6])
Expected Output: [-5, -4, -3, -2, 0, 6]
Explanation: Negative values merge correctly because comparison, not magnitude, drives selection.
Input: ([1, 2, 3], [4, 5, 6])
Expected Output: [1, 2, 3, 4, 5, 6]
Explanation: Disjoint ranges: list1 fully drains before any element of list2 is taken.
Input: ([10, 20], [1, 2, 3])
Expected Output: [1, 2, 3, 10, 20]
Explanation: list2 fully drains first, then the remainder of list1 is appended.
Hints
- Walk both lists with two pointers, always taking the smaller current value next. Use <= (not <) when values are equal so the merge is stable and duplicates are kept.
- When one list is exhausted, append the entire remainder of the other list — it is already sorted.
- For the in-place iterative version on real nodes, use a dummy head node so you never special-case the first element; for the recursive version, return the smaller head and recurse on the rest.