InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Merge Two Sorted Lists

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug