00:00

Problem Statement

Input/Output Examples

Visual Explanation

If the lists have different lengths, switching lists cancels out the difference. If they never intersect, both pointers reach null at the same time, and the loop ends.

Approaches

The switching trick uses no extra memory. The set-based approach is easier to explain but stores one list.

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. Both approaches visit each node a constant number of times; only the set approach needs memory for one list.

Interview Tips and Recommended Approach

  • Compare nodes, not values. Two different nodes can hold the same number.
  • Explain why the pointers meet. Both travel a + c + b steps, where c is the shared part.
  • Know the length-difference method. Advancing the longer list by the length difference first also works in O(1) space.
  • Do not modify the lists. Tricks that mark or relink nodes break the input.

Recommended Approach: Switching Two Pointers

Why: it uses constant extra memory, needs no length calculation and is only a few lines long.