Circular Array Loop
01 · Problem
You are given a circular array nums of non-zero integers. Each value is a move instruction: from index i, a positive nums[i] moves you nums[i] steps forward and a negative one moves you |nums[i]| steps backward. Because the array is circular, stepping past the last element wraps to the first and vice versa, so the next index is (i + nums[i]) mod n, taken as a non-negative remainder.
A cycle is a sequence of indices seq[0] -> seq[1] -> ... -> seq[k-1] -> seq[0] produced by these moves such that:
- every
nums[seq[j]]has the same sign (all forward or all backward), and k > 1, i.e. a single index that jumps back onto itself does not count.
Return true if such a cycle exists anywhere in nums, otherwise false.
02 · Examples
nums = [2,-1,1,2,2]
true
0 -> 2 -> 3 -> 0 is a cycle of length 3 in which every move goes forward.
nums = [-1,-2,-3,-4,-5,6]
false
Index 5 moves 6 steps and lands on itself, a length-1 loop that does not count. Every other path eventually mixes backward moves with index 5's forward move.
nums = [1,-1,5,1,4]
true
3 -> 4 -> 3 is a forward-only cycle of length 2. (0 -> 1 -> 0 also loops, but it mixes directions, so it does not count on its own.)
03 · Constraints
- 011 <= nums.length <= 5000
- 02-1000 <= nums[i] <= 1000
- 03nums[i] != 0
04 · Optimal complexity
- Time
- O(n)
- Space
- O(1)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.