Circular Array Loop - Problem

You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:

  • If nums[i] is positive, move nums[i] steps forward
  • If nums[i] is negative, move abs(nums[i]) steps backward

Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.

A cycle in the array consists of a sequence of indices seq of length k where:

  • Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k-1] -> seq[0] -> ...
  • Every nums[seq[j]] is either all positive or all negative
  • k > 1 (cycle must have more than one element)

Return true if there is a cycle in nums, or false otherwise.

Input & Output

Example 1 — Valid Cycle
$ Input: nums = [2,-1,1,-2]
Output: false
💡 Note: Starting from any index, we cannot form a valid cycle. From index 1: 1→0→2→3→1, but this cycle has mixed directions (nums[0]=2 positive, nums[1]=-1 negative), violating the same-direction rule.
Example 2 — No Valid Cycle
$ Input: nums = [-1,2]
Output: false
💡 Note: Index 0 moves to index 1, index 1 moves to index 1 (self-loop). Self-loops are invalid since cycle length must be > 1.
Example 3 — Direction Change
$ Input: nums = [-2,1,-1,-2,-2]
Output: false
💡 Note: No valid cycle exists because paths either lead to direction changes or form invalid cycles.

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -1000 ≤ nums[i] ≤ 1000
  • nums[i] ≠ 0

Visualization

Tap to expand
Circular Array Loop - Path Marking INPUT 2 idx 0 -1 idx 1 1 idx 2 -2 idx 3 Input Array: nums = [2, -1, 1, -2] ALGORITHM STEPS 1 Start at each index Try finding cycle from idx 0 2 Follow the path 0 --> 2 --> 3 --> 1 --> 0 3 Check direction Must be same sign (+/-) 4 Mark visited paths Avoid revisiting nodes Path Trace: 0 2 3 Mixed signs - invalid cycle FINAL RESULT Valid Cycle Found! 0 2 3 1 Output: true Cycle length k = 4 > 1 [OK] Valid cycle exists Key Insight: Path Marking uses the array itself to track visited nodes by setting them to 0. Use slow/fast pointers to detect cycles. A valid cycle must have: (1) same direction for all elements, (2) length > 1, and (3) not be a self-loop. Time: O(n), Space: O(1) with in-place marking. TutorialsPoint - Circular Array Loop | Optimized with Path Marking
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 15
34.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen