Skip to problem
←

Merge Two Sorted Lists

Easy 0 attempts

Given the heads l1 and l2 of two singly linked lists sorted in non-decreasing order, merge them into one sorted list and return its head.

Keep every input value, including duplicates. Either list may be empty; if both are empty, return null. You may reuse and relink input nodes.

The examples display lists as value arrays, but your function receives head nodes and must return a head node, not an array. For [1,2,4] and [1,3,4], both copies of 1 and 4 remain in [1,1,2,3,4,4].

Function contract

Implement mergeTwoLists(l1, l2). Each displayed array is converted to a singly linked list with val and next properties. An empty array becomes null.

Output: Return the merged head node, or null if both lists are empty. The runner displays its values as an array.

Example 1

Input
l1 = [1,2,4]
l2 = [1,3,4]
Output
[1,1,2,3,4,4]

Example 2

Input
l1 = []
l2 = []
Output
[]
Constraints
  • 0 to 50 nodes per list
  • -100 <= Node.val <= 100
  • Each input list is sorted in non-decreasing order

Iterative Merge

Use a dummy node to avoid special handling for the first output node. Compare the current heads, append the smaller node, and advance only that input pointer. Once one list is exhausted, attach the remaining sorted suffix from the other list. Return dummy.next so the placeholder itself is excluded. Existing nodes are relinked; no output-sized buffer is allocated.

javascript
function mergeTwoLists(l1, l2) {
  const dummy = { val: 0, next: null };
  let curr = dummy;
  while (l1 && l2) {
    if (l1.val <= l2.val) {
      curr.next = l1;
      l1 = l1.next;
    } else {
      curr.next = l2;
      l2 = l2.next;
    }
    curr = curr.next;
  }
  curr.next = l1 || l2;
  return dummy.next;
}

Time: O(m + n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript