Back to Dashboard

Cycle in a Circular Array

Hard

Problem Statement

We are given an array containing positive and negative numbers. Suppose the array contains a number ‘M’ at a particular index. Now, if ‘M’ is positive we will move forward ‘M’ indices and if ‘M’ is negative move backwards ‘M’ indices. You should assume that the array is circular which means two things:

If, while moving forward, we reach the end of the array, we will jump to the first element to continue the movement. If, while moving backward, we reach the beginning of the array, we will jump to the last element to continue the movement. Write a method to determine if the array has a cycle. The cycle should have more than one element and should follow one direction which means the cycle should not contain both forward and backward movements.

Examples

Example 1:

  • Input: [1, 2, -1, 2, 2]
  • Output: true

Approach 1 Slow Fast Pointers:

class Solution {
    public boolean circularArrayLoop(int[] nums) {
       for (int i = 0; i < nums.length; i ++) {
        var isForward = nums[i] > 0;
        int slow = i, fast = i;
        do {
            slow = next(nums, slow, isForward);
            fast = next(nums, fast, isForward);
            if (fast != -1) {
                fast = next(nums, fast, isForward);
            }
        } while (slow != -1 && fast != -1 && slow != fast);
        
        if (slow != -1 && slow == fast) {
            return true;
        }
       }
       return false;
    }

    // (i + jump + N) % N
    private int next(int[] nums, int i, boolean isForward) {
        var direction = nums[i] > 0;
        if (direction != isForward) {
            return -1;
        }
        var nextIndex = (i + nums[i] + nums.length) % nums.length;
        if (nextIndex < 0) {
            nextIndex += nums.length;
        }
        if (i == nextIndex) {
            return -1;
        }
        return nextIndex;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArrayCycleSlow Fast Pointers

Date

2026-02-11
View Problem Source