Ad platform~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-457cycle-detection · two-pointers
An ad carousel has n banner slots in a ring. Each slot has a skip rule: a positive number hops forward that many slots, a negative number hops back, and the ring wraps at both ends.
A viewer who keeps tapping from some slot can get stuck in a steady loop: two or more slots that repeat, where every hop goes the same way. With 100,000 slots, following every start for 100,000 hops is too slow.
Write has_steady_loop(hops).
s the next slot is (s + hops[s]) wrapped into the range 0 to n - 1.n, is a loop of one slot. It does not count.true if a steady loop exists, reached from any start slot, and false otherwise.Input: hops = [2, -1, 1, 2, 2]
Output: trueFrom slot 0 the hops go 0, 2, 3, 0, and all of them are positive, so slots 0, 2 and 3 are a steady loop. Two walkers start on slot 0. In each round slow takes one hop and fast takes two.
| Round | slow |
fast |
|---|---|---|
| start | 0 | 0 |
| 1 | 2 | 3 |
| 2 | 3 | 2 |
| 3 | 0 | 0 |
The walkers meet on slot 0, so the walk is inside a loop, and no hop turned round on the way.
Input: hops = [-1, 2]
Output: falseFrom slot 0 the hop goes back to slot 1, and slot 1 hops forward by 2 onto itself. There is no steady loop.
Input: hops = [-2, 1, -1, -2, -2]
Output: falseSlots 1 and 2 loop: slot 1 hops forward to slot 2, and slot 2 hops back to slot 1. The two hops go opposite ways, so it is not steady.
1 ≤ len(hops) ≤ 100,000-10^6 ≤ hops[s] ≤ 10^6Following 100,000 hops from each of 100,000 starts is 10^10 steps, far beyond a single second.
Slots that lead nowhere new need not be walked again. Each slot is walked a few times in all, so the whole answer takes about a million steps.