CodingNodes / Linked List / Merge Two Sorted Lists System design Space play · ←→ step · R restart

Problem

You get the heads of two linked lists, list1 and list2. Each one is already sorted from smallest to largest.

Join them into one sorted list by re-linking the existing nodes, and return its head. When two values are equal, take the node from list1 first.

Constraints

  • 0 ≤ length of each list ≤ 50
  • -100 ≤ Node.val ≤ 100
  • Both lists are sorted in non-decreasing order

Examples: pick one to animate

Solutions

TimeO(n + m) SpaceO(1)

Time: Each pass moves one node into the result, and every node is moved at most once. Leftovers are attached in one step.

Space: Only the dummy node and a few pointers are used. The result is built from the original nodes.

Hold a dummy node and a tail pointer. Compare the two front nodes, link the smaller one after tail, and move that list forward. When one list runs out, attach the other list as it is.