Ctrl K

Ride Until a Repeat

Hard
A city has n stops numbered 0 to n - 1. Exactly one route leaves each stop: from stop i you can only ride to stop next_stop[i], which is always a different stop. A traveller starts at stop x and keeps riding until they arrive at a stop they have already visited on this trip, and then they stop. Return an array answer where answer[i] is the number of different stops the traveller visits when starting from stop i.
Example 1
next_stop=[1, 0] → [2, 2]

From 0 we go to 1 and then back to 0, visiting 2 different stops. Starting from 1 is the same.

Example 2
next_stop=[2, 2, 3, 1] → [4, 3, 3, 3]

From 0: 0 → 2 → 3 → 1 → 2 (seen before), so 4 stops are visited. Stops 1, 2 and 3 form a loop of three, so each of them gets 3.

Example 3
next_stop=[1, 2, 1, 2] → [3, 2, 2, 3]
Constraints
  • 2 ≤ n ≤ 10⁵, n = len(next_stop)
  • 0 ≤ next_stop[i] ≤ n − 1
  • next_stop[i] ≠ i
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Uphill Walk HardThief and Guard HardMouse, Cat and Cheese HardMost Repeated Colour on a Path HardUphill-Only Walks Hard
loading Python…
Input
next_stop=[1, 0]
Expected
[2, 2]

Run checks the first 3 tests in your browser. Submit checks all 57 tests on the server, hidden ones included.