~/DHRUVUpskilling
← board/DSA/Fast and Slow Pointer/dsa-fast-and-slow-pointer-04
Backlog·queued

Circular Array Loop

DifficultyMedium
PatternFast and Slow Pointer
TrackDSA
tl;dr

An input array, nums containing non-zero integers is given, where the value at each index represents the number of places to skip forward (if the value is positive) or backward (if the value is negative). When skipping forward or backward, wrap around if you reach either end of the array. For this reason, we are calling it a circular array. Determine if this circular array has a cycle. A cycle is a sequence of indices in the circular array characterized by the following: The same set of indices is repeated when the sequence is traversed in accordance with the aforementioned rules. The length of the sequence is at least two. The loop must be in a single direction, forward or backward. It should be noted that a cycle in the array does not have to originate at the beginning. A cycle can begin from any point in the array.

full write-up

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • −5000 ≤ nums[i] ≤ 5000
  • nums[i] ≠ 0

Examples

Example 1

Input: nums = [2, -1, 1, 2, 2]

Explanation: Starting at index 0: value is 2, so move forward 2 steps → index 2. At index 2: value is 1, so move forward 1 step → index 3. At index 3: value is 2, so move forward 2 steps → index 0. This traces the cycle 0 → 2 → 3 → 0, which has length ≥ 2 and moves in a single direction (forward).

Output: TRUE

Example 2

Input: nums = [-1, -2, -3, -4, -5, -6]

Explanation: Starting at index 0: value is -1, so move backward 1 step → index 5. At index 5: value is -6, so move backward 6 steps → index 5 (wraps back to itself). This forms a cycle of length 1 at a single index, which does not satisfy the "length at least two" condition.

Output: FALSE