sagelearnai

Circular Array Loop

Difficulty: Medium · Pattern: Fast & Slow Pointers · LeetCode #457

nums is a circular array of non-zero integers. From index i you jump nums[i] steps (forward if positive, backward if negative, wrapping around). Return true if there is a cycle where (a) every jump in it goes in the same direction and (b) its length is greater than 1.

Examples

text
[2,-1,1,2,2]  →  true    (0 → 2 → 3 → 0)
[-1,-2,-3,-4,-5,6]  →  false  (the only cycle is 5 → 5, length 1)
[1,-1,5,1,4]  →  true    (3 → 4 → 3)

Hints

  1. From each start, run fast/slow pointers, but stop as soon as a step would change direction or would be a self-loop.
  2. To get O(n), mark every index on a failed path as dead (set it to 0) so it's never explored again.

Approach

nxt(i) = (i + nums[i]) % n (Python's % already wraps negatives correctly; in JS use ((x % n) + n) % n).

For each start i with nums[i] != 0:

  • Move slow 1 step and fast 2 steps, but only while each step keeps the same sign as nums[i].
  • If they meet: if slow == nxt(slow), it's a self-loop, so this path fails. Otherwise return true.
  • On failure, walk again from i while the sign is unchanged, setting nums[j] = 0. Those indices can't be part of a valid cycle.

Each index is marked at most once, so the total is O(n) with O(1) extra space.

Complexity

Time: O(n). Space: O(1) for the marking version (O(n) for the state array).

Python solution
def circularArrayLoop(nums):
    n = len(nums)
    nxt = lambda i: (i + nums[i]) % n
    for i in range(n):
        if nums[i] == 0:
            continue
        d = nums[i] > 0
        slow, fast = i, i
        while True:
            # advance slow by 1, fast by 2, all moves must keep direction d
            s1 = nxt(slow)
            f1 = nxt(fast)
            if (nums[f1] > 0) != d or nums[f1] == 0:
                break
            f2 = nxt(f1)
            if (nums[s1] > 0) != d or (nums[f2] > 0) != d or nums[f2] == 0:
                break
            slow, fast = s1, f2
            if slow == fast:
                if slow == nxt(slow):
                    break
                return True
        j = i
        while nums[j] != 0 and (nums[j] > 0) == d:
            k = nxt(j)
            nums[j] = 0
            j = k
    return False
JavaScript solution
function circularArrayLoop(nums) {
  // For each start, follow same-direction jumps with a visited-in-this-walk set.
  const n = nums.length, nxt = (i) => (((i + nums[i]) % n) + n) % n;
  const state = new Array(n).fill(0); // 0 = unseen, 1 = on current path, 2 = done (no valid cycle)
  for (let s = 0; s < n; s++) {
    if (state[s]) continue;
    const dir = nums[s] > 0, path = [];
    let i = s;
    while (state[i] === 0 && (nums[i] > 0) === dir) {
      state[i] = 1; path.push(i);
      const j = nxt(i);
      if (j === i) break;                  // self-loop: invalid
      if (state[j] === 1 && (nums[j] > 0) === dir) return true;
      i = j;
    }
    for (const p of path) state[p] = 2;
  }
  return false;
}