Skip to content

Merge Sorted Chains

Easy#two-pointers#dummy-node~20 min

The mission

Problem

Two singly linked lists are each already sorted in non-decreasing order. Splice them into one sorted list by relinking the existing nodes rather than creating new ones. Return the head of the merged list, which is empty when both inputs are empty.

Examples

Input:  a = 1 -> 4 -> 6, b = 2 -> 3
Output: 1 -> 2 -> 3 -> 4 -> 6
Input:  a = empty, b = 7
Output: 7
Why:    edge case, one side runs out before the loop starts
Input:  a = empty, b = empty
Output: empty
Why:    edge case, there is nothing to merge

Hints

0 / 3

Target time
O(n + m)
Target space
O(1)

Constraints

  • both lists are sorted in non-decreasing order
  • either list may be empty

Stuck on the idea rather than the code? Merge Two Sorted Lists covers it.

Python 3Ctrl+Enter runs