Engineering platform~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-141cycle-detection · linked-lists · two-pointers
You work on the gateway behind an app. When a request fails at one endpoint, the gateway retries at a fallback endpoint. The endpoints sit in a table: slot i holds after[i], the slot to try when slot i fails, or -1 when there is no fallback.
A wrong setting can make the fallbacks go round in a loop, and a request would retry for ever. The check runs on every request, so it must use a fixed amount of memory.
Write retry_loops(after, start).
after is the table. Each value is -1 or a slot number below the length of the table.start is the slot where a request starts.start. Return true when the chain never ends, because some slot repeats, and false when it reaches -1.Input: after = [1, 2, 3, 1], start = 0
Output: true| Round | slow | fast | What happens |
|---|---|---|---|
| start | 0 | 0 | both walkers stand on slot 0 |
| 1 | 1 | 2 | slow takes 1 step, fast takes 2 |
| 2 | 2 | 1 | fast goes 2 → 3 → 1, round the loop |
| 3 | 3 | 3 | fast goes 1 → 2 → 3: both are on slot 3, so the chain loops |
The chain is 0 → 1 → 2 → 3 → 1 → 2 → 3 → ... The slots 1, 2 and 3 form the loop, and slot 0 is the way in.
Input: after = [1, 2, 3, -1], start = 0
Output: falseThe chain 0 → 1 → 2 → 3 ends at -1. Fast reaches the end first, and the walkers never meet.
Input: after = [0], start = 0
Output: trueA slot whose fallback is itself is the smallest loop.
1 ≤ length of after ≤ 10^5-1 ≤ after[i] ≤ length of after - 10 ≤ start ≤ length of after - 1Following the chain once is at most 10^5 steps, so the time is not the problem. Keeping a list of visited slots 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 grows with the chain, and the statement asks for a fixed amount of memory. Two walkers at different speeds need no record at all: O(n) time and O(1) extra memory.
A note on the tests: the judge measures time, not extra memory, and a hash set of 10^5 slots fits easily in the memory limit. So a hash set passes, and only the list scan times out. The fixed-memory walk is what this problem teaches, and what an interviewer asks for once you mention the set.