Ctrl K

One-Way Jump Cycle

Medium
Cells are laid out in a circle, and cell 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?
Example 1
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.

Example 2
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.

Example 3
jumps=[1, -1] → False

The cycle 0 → 1 → 0 exists, but 0 jumps forward while 1 jumps backward.

Constraints
  • 1 ≤ len(jumps) ≤ 10⁵
  • -1000 ≤ jumps[i] ≤ 1000
  • jumps[i] ≠ 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Subsequence of One Word Only MediumPairs With a Fixed Gap MediumTriples Hitting the Target MediumWord Growth Chain MediumSquare Equals a Pair Product Medium
loading Python…
Input
jumps=[1, 2, -1, 2]
Expected
True

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