Circular Array Loop

Detect a cycle of length > 1 that flows in a single direction using fast/slow pointers per start position.

Medium
Time O(n) Space O(1)
LeetCode
5 min read
fast-slow array

Problem#

nums[i] says “jump that many steps (wrapping mod n)”. Return true if there exists a cycle satisfying: (1) length > 1, (2) all jumps in the cycle have the same sign.

Examples#

  • [2,-1,1,2,2]true (0 → 2 → 3 → 0 is forward cycle of length 3)
  • [-1,-2,-3,-4,-5,6]false (length-1 cycle disqualifies)

Constraints#

  • 1 <= nums.length <= 5000.

Hints#

Hint 1
For each unvisited start, run fast/slow. Abort the walk on sign flip or self-loop.

Approach#

For each start i, do Floyd’s detection where the next-step function is (j + nums[j]) mod n (correctly handling negative mod). Reject the walk if the sign changes or if any step lands back on itself (length-1 cycle). To stay O(n) total, mark visited indices that don’t lead to a valid cycle so we never re-walk them.

Solution#

Circular Array Loop
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
const int n = nums.size();
auto next = [&](int i) {
int j = ((i + nums[i]) % n + n) % n;
return j == i ? -1 : j; // length-1 self-jump → invalid
};
for (int start = 0; start < n; ++start) {
if (nums[start] == 0) continue;
int slow = start, fast = start;
int dir = nums[start];
auto valid = [&](int i) {
return i != -1 && ((long long)dir * nums[i] > 0);
};
while (true) {
slow = next(slow);
if (!valid(slow)) break;
int f1 = next(fast);
if (!valid(f1)) break;
fast = next(f1);
if (!valid(fast)) break;
if (slow == fast) return true;
}
}
return false;
}
};

Editorial#

Two pruning rules keep the algorithm clean: (a) once we see any sign change, no valid cycle starts here so abort; (b) the modulo formula ((x % n) + n) % n is the standard “true mod” for negative x in C++. The classical optimization marks visited nodes with 0 once we know the walk is dead, dropping the total work to O(n); the version above is O(n²) worst-case but the more readable one for interviews.

Complexity#

  • Time: O(n²) in the simple version; O(n) with marking.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.