MediumPythonJavaScriptTypeScript

Merge Two Sorted Linked Lists

Data StructuresLinked ListSorting

You are given two sorted arrays. Your task is to:
1. Build a singly-linked list from each array.
2. Merge the two sorted lists in O(n + m) by relinking nodes — no new
ListNode instances allowed during the merge step.
3. Return the merged sequence as a plain array.

solve(a, b) receives two sorted number arrays and must return a single
sorted array using the approach above.

Node structure

class ListNode { constructor(val, next = null) }

Examples

solve([1, 3, 5], [2, 4, 6])  → [1, 2, 3, 4, 5, 6]
solve([],        [1, 2])     → [1, 2]
solve([5],       [1, 3, 7])  → [1, 3, 5, 7]

Constraints

  • Values may include duplicates.
  • Either or both inputs may be empty.
  • Time: O(n + m) · Space: O(1) extra (only the output array).

Sample tests

Test #1Two equal-length sorted lists interleave perfectly
Input: [[1,3,5],[2,4,6]]
Output: [1,2,3,4,5,6]
Test #2First list is empty — return second as-is
Input: [[],[1,2,3]]
Output: [1,2,3]
Test #3Single-element list merges into the middle
Input: [[5],[1,3,7]]
Output: [1,3,5,7]