Skip to content
Decoder

Intersection of Two Linked Lists

Easy

Problem

You get the heads of two singly linked lists, a and b. At some point they may merge into one shared tail: from that node on, both lists use the very same node objects. Return the first shared node, or None (null in TypeScript) if the lists never meet. Equal values do not count; it must be the same node object. Do not change either list, and try for O(1) extra memory.

Example 1

Input
a: 4
Output
1 \

Example 2

Input
8
Output
4 -> 5

Example 3

Input
b: 5
Output
6 -> 1 /

Example 4

                                →  the node holding 8

Example 5

Input
a: 2
Output
6 -> 4

Example 6

Input
b: 1
Output
5 → None

The tests build lists that share a tail and check that you return the exact first shared node.

Constraints

  • 0 <= number of nodes in each list <= 3 * 10^4
  • 1 <= Node.val <= 10^5
  • Neither list contains a cycle.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.