Online store~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-142cycle-detection · linked-lists · two-pointers
An online store keeps its redirect rules in a table. Page i redirects visitors to page after[i], or to nobody when after[i] is -1, which means the page is a real page.
A wrong rule can send visitors round in a circle. Support needs the page where the circle begins, because that is the rule to fix. The table can hold 100,000 pages, and the check must use a fixed amount of memory.
Write loop_start_page(after, start).
after is the table. Each value is -1 or a page number below the length of the table.start is the page where a visitor starts.start. When the visitor reaches -1, return -1. When the redirects loop, return the first page on the visitor's path that belongs to the loop. That is the page the visitor reaches again after going round.Input: after = [1, 2, 3, 4, 5, 2], start = 0
Output: 2| Phase | Step | First walker | Second walker |
|---|---|---|---|
| 1 | start | slow on 0 | fast on 0 |
| 1 | 1 | slow on 1 | fast on 2 |
| 1 | 2 | slow on 2 | fast on 4 |
| 1 | 3 | slow on 3 | fast on 2 (4 → 5 → 2) |
| 1 | 4 | slow on 4 | fast on 4: they meet |
| 2 | start | slow stays on 4 | a new walker starts on 0 |
| 2 | 1 | slow on 5 | walker on 1 |
| 2 | 2 | slow on 2 | walker on 2: they meet, return 2 |
The redirects go 0 → 1 → 2 → 3 → 4 → 5 → 2. Pages 0 and 1 lead into the loop, and the loop is 2, 3, 4, 5. The meeting page, 4, is not the answer, but it leads to it.
Input: after = [1, 2, -1], start = 0
Output: -1The redirects 0 → 1 → 2 end at a real page. There is no loop.
Input: after = [0], start = 0
Output: 0A page that redirects to itself. The loop begins at the page where the visitor starts.
1 ≤ length of after ≤ 10^5-1 ≤ after[i] ≤ length of after - 10 ≤ start ≤ length of after - 1Following the redirects once is at most 10^5 steps. Keeping a list of the pages visited and scanning it before every step makes about n^2 / 2 comparisons: 5 × 10^9 at this size, which is too slow.
A hash set fixes the time, but it holds every page, and the statement asks for a fixed amount of memory. Two phases of walking need only a few variables: O(n) time and O(1) extra memory.
A note on the tests: the judge measures time, not extra memory, so a hash set passes and only the list scan times out. The two-phase walk is what this problem teaches, and what an interviewer asks for next.