InterviewPrepKit

Home / Coding / Linked List

Merge Two Sorted Lists

easy Original β†—
Solving tips
  • This is the merge step of merge sort: the next node is always the smaller of the two current heads, one comparison per output node.
  • Use a dummy head so you always append to tail.next and return dummy.next, collapsing the empty-result and first-node special cases.
  • After the loop, attach the remaining tail with 'tail.next = list1 if list1 else list2' or the leftover longer list silently disappears.
  • Splice existing nodes (don't allocate new ones); O(n + m) time, O(1) space iteratively, and use '<=' to keep the merge stable.

Problem

You are given the heads of two singly linked lists, list1 and list2, each already sorted in non-decreasing order. Splice the two lists together into one sorted list β€” reuse the existing nodes rather than allocating new ones β€” and return the head of the merged list.

Examples

  • Input: list1 = 1 -> 2 -> 4, list2 = 1 -> 3 -> 4 β†’ Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4 Interleave the nodes so the result stays sorted.
  • Input: list1 = (empty), list2 = (empty) β†’ Output: (empty) Nothing to merge.
  • Input: list1 = (empty), list2 = 0 β†’ Output: 0 One empty list means the answer is just the other list.

Constraints

  • Each list has [0, 50] nodes.
  • -100 <= Node.val <= 100
  • Both lists are sorted in non-decreasing order.

Think about it first

Hint 1 Both lists are already sorted. At any moment, which node must come next in the merged output? You only ever need to compare two nodes.
Hint 2 Building a list forward is awkward when you don't yet have a first node. A throwaway "dummy" head node lets you always append to tail.next and return dummy.next at the end.
Hint 3 Repeatedly: compare the two front nodes, link the smaller one onto the tail of the result, and advance that list. When one list runs out, attach the entire remainder of the other β€” it's already sorted.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.