KatInterview

Find Where Two Linked Lists Merge

Linked ListsAuto-graded · 17 test cases
HardAuto-gradedLinked Liststwo-pointerslinked-listspointer-manipulation

Last updated

Tests pointer manipulation and list traversal to locate the merge point of two singly linked lists in linear time with constant space.

You are given two singly linked lists that may share a common tail. Each list is represented by a private prefix followed by a shared suffix. Your task is to identify the index at which the shared portion begins within the first list.

More precisely, you receive:

  • prefix_a: the values unique to the first list, before any merging occurs
  • prefix_b: the values unique to the second list, before any merging occurs
  • shared_suffix: the values that both lists share after they merge

If the lists do not merge (the shared suffix is empty), return None. Otherwise, return the zero-based index in the first list where the shared suffix starts.

For instance, if the first list is [4, 1, 8, 4, 5] and the shared portion begins at index 2, the private prefix is [4, 1] and the shared suffix is [8, 4, 5].

The index you return is always len(prefix_a) when a shared suffix exists, because the suffix immediately follows the prefix in the concatenated list.

Constraints

  • 0 ≤ len(prefix_a), len(prefix_b) ≤ 10⁴
  • 0 ≤ len(shared_suffix) ≤ 10⁴
  • All values are integers in the range [-10⁹, 10⁹]
  • The concatenated lists each have at most 2 × 10⁴ nodes total
  • If shared_suffix is empty, the lists do not intersect

Examples

Example 1

Input: find_merge_index([4, 1], [5, 6, 1], [8, 4, 5])

Output: 2

Example 2

Input: find_merge_index([2, 6, 4], [1, 5], [])

Output: None

Hints

Hint 1

The merge point is where both lists begin sharing the exact same sequence of nodes, not just matching values.

Hint 2

When a shared suffix exists, it always starts immediately after the private prefix of each list.

Hint 3

The index of the merge point in the first list is simply the length of its private prefix.