dsa · easy

Shared Tail of Two Lists

Two singly linked lists are given by their node-value arrays head_a and head_b. They may share a tail: a non-empty suffix of equal values that both chains keep to the end. Return the first value of that shared suffix. If the two arrays share no suffix, return 0.

Arguments

Values are positive, so 0 cannot be a real node value.

Example

head_a = [4,1,8,4,5], head_b = [5,0,8,4,5]

Reading from the back, both end …, 8, 4, 5. The first shared tail value is 8.

[2,3] and [7,9] share no suffix → 0.

Constraints

0 <= head_a.length, head_b.length <= 4*10^4 1 <= node value <= 10^5 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[4,1,8,4,5]
[5,0,8,4,5]

Expected:
8

Example 2

Input:
[2,3]
[7,9]

Expected:
0

Example 3

Input:
[1,2,3]
[1,2,3]

Expected:
1

Open in the Dojo editor