i holds a non-zero number jumps[i]. A token standing on cell i moves jumps[i] cells: forward if the number is positive, backward if it is negative. The circle wraps around: stepping forward from the last cell leads to the first, and stepping backward from the first leads to the last.
A **cycle** is a sequence of cells the token keeps going around forever, such that:
- it contains more than one cell;
- all of its jumps go the same way, either all forward or all backward.
Return True if the array contains at least one such cycle, and False otherwise.
Can you do it in O(n) time with O(1) extra space?jumps=[1, 2, -1, 2] → True
From cell 1 a jump of 2 forward lands on 3, and from 3 a jump of 2 forward wraps around back to 1. The cycle 1 → 3 → 1 has length 2 and both jumps go forward.
jumps=[3, -2, 4] → False
Cell 0 jumps 3 forward and lands on itself, and a length-1 cycle does not count. The path 1 → 2 → 0 never closes, and from 0 there is only that self-loop. The answer is False.
jumps=[1, -1] → False
The cycle 0 → 1 → 0 exists, but 0 jumps forward while 1 jumps backward.
jumps[i] ≤ 1000jumps[i] ≠ 0jumps=[1, 2, -1, 2]
True
Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.