An airport shuttle route is modeled as a singly linked list of stop codes, front to back. Instead of ending, the LAST stop's next-hop may point back to an EARLIER stop, forming a loop. You are given the stop codes and, separately, the 0-indexed position that the last stop's next-hop points to (or -1 if the route simply ends with no loop). Print the number of stops that belong to the loop (0 if there is no loop).
Line 1: an integer n — the number of stops.
Line 2: n space-separated integers — the stop codes, front to back.
Line 3: an integer pos — the 0-indexed stop that the last stop's next-hop points to, or -1 if there is no loop.
A single integer: the number of stops in the loop (0 if there is no loop).
Example 1
Input
5 1 2 3 4 5 2
Expected
3
Explanation
The last stop loops back to index 2, so stops at indices 2,3,4 (3 stops) form the loop.
Example 2
Input
4 9 8 7 6 -1
Expected
0
Explanation
pos is -1, so the route has no loop and the answer is 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →