00:00

Problem Statement

Input/Output Examples

Visual Explanation

A dummy node in front of the result means the first real node is handled like every other node. When one list ends, the remaining list is already sorted, so it is attached with a single assignment.

Approaches

Both approaches relink the existing nodes. One uses a loop with a dummy head; the other expresses the merge recursively.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n and m are the lengths of the lists. Each node is linked once. The loop uses constant memory; the recursion uses one stack frame per node.

Interview Tips and Recommended Approach

  • Use a dummy node. It removes the special case for choosing the first node.
  • Attach the remainder in one step. There is no need to loop over what is left.
  • Prefer the loop for long lists. The recursive version can throw StackOverflowError.
  • Know where it is used: this merge is the core of merge sort on linked lists and of merging k sorted lists.

Recommended Approach: Iterative With a Dummy Node

Why: it relinks nodes in place with constant extra memory and has no recursion depth limit.