Intersection of Two Linked Lists
easyLinked List+10 XPTime limit 2s
Two singly linked lists may merge: from some node on, they share the same nodes (the same objects in memory, not just equal values) until the end. Find the node where they meet.
Input:
- line 1:
a b c— list A hasanodes of its own, list B hasbnodes of its own, and then both continue intocshared nodes - line 2: the
avalues of A's own part (may be empty) - line 3: the
bvalues of B's own part (may be empty) - line 4: the
cvalues of the shared part (may be empty)
The starter code builds the real structure: A = own part of A → shared part, B = own part of B → the same shared nodes.
Output: the positions of the meeting node: i j, where i is its 0-based index in list A and j its index in list B — or none if the lists don't meet.
Constraints: 0 ≤ a, b, c ≤ 3·10⁴, 1 ≤ a + c, 1 ≤ b + c; values are between 1 and 10⁵ and may repeat, so compare nodes, not values.
The trick: walk pointer p through A then B, and q through B then A. They travel the same total distance, so they reach the meeting node at the same moment — or both reach the end (null) together. Count steps to get the indices.
Sample input 1
2 3 3 4 1 5 6 1 8 4 5
Sample output 1
2 3
Sample input 2
3 1 0 2 6 4 1 5
Sample output 2
none
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).