Linked Lists · Coding problem

Intersection of Two Linked Lists

A free coding problem from the Linked List Intersection skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

Two singly linked lists may join partway along and share every node from there to the end, like two roads merging into one. Return the value of the first shared node, or -1 if the lists never meet.

Input format

Six lines: a (the length of list A's own prefix), then those a values; b (the length of list B's own prefix), then those b values; c (the length of the shared suffix), then those c values. A length of 0 is followed by no values, and c = 0 means the lists don't meet.

Example

Input:
2
3 7
1
6
3
2 9 4
Output:
2

List A is 3 -> 7 -> 2 -> 9 -> 4 and list B is 6 -> 2 -> 9 -> 4; from the 2 on, they are the same nodes.

Solve it in O(lenA + lenB) time with O(1) extra space, so no HashSet of visited nodes.

Constraints

  • 0 <= a, b <= 1000
  • 0 <= c <= 1000
  • At least one of the lists is not empty
  • If c > 0, the lists genuinely share those trailing nodes (not just equal values)

How it's graded

  • Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

Solve it Intersection of Two Linked Lists free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime