457. Circular Array Loop
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, and
- If nums[i] is negative, move 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
Return true if there is a cycle in nums, or false otherwise.
Example 1:
Example 2:
Example 3:
Constraints:
- 1 <= nums.length <= 5000
- -1000 <= nums[i] <= 1000
- nums[i] != 0
From: LeetCode
Link: 457. Circular Array Loop
Solution:
Ideas:
1. Function next: Calculates the next index in the circular manner, ensuring that we wrap around the array correctly.
2. Main Loop: Iterates through each index, treating it as a potential starting point for a cycle.
3. Direction Check: The cycle must be in one direction (all positive or all negative). We set isForward based on the sign of the starting index.
4. Floyd’s Cycle Detection: Use a “slow” and “fast” pointer approach to detect if a cycle exists.
- Both pointers move in the same direction (either forward or backward).
- If slow meets fast, a cycle is detected.
5. Single Element Cycle Check: If the detected cycle has only one element, we skip it, as cycles of size k = 1 are invalid.
6. Marking Visited Elements: To avoid revisiting elements, set them to zero once they’ve been confirmed not to be part of a valid cycle.
Code:
int next(int* nums, int numsSize, int index) {
int n = numsSize;
return ((index + nums[index]) % n + n) % n; // Move in a circular manner
}
bool circularArrayLoop(int* nums, int numsSize) {
for (int i = 0; i < numsSize; i++) {
if (nums[i] == 0) continue;
int slow = i, fast = i;
bool isForward = nums[i] > 0;
while (true) {
slow = next(nums, numsSize, slow);
fast = next(nums, numsSize, fast);
if (nums[fast] > 0 != isForward || nums[slow] > 0 != isForward) break;
fast = next(nums, numsSize, fast);
if (nums[fast] > 0 != isForward || nums[slow] > 0 != isForward) break;
if (slow == fast) {
if (slow == next(nums, numsSize, slow)) break; // Cycle of length 1
return true;
}
}
slow = i;
int val = nums[i];
while (nums[slow] == val) {
int nextIndex = next(nums, numsSize, slow);
nums[slow] = 0; // Mark as visited
slow = nextIndex;
}
}
return false;
}