Leetcode 457. Circular Array Loop
You are given a circular array nums
of positive and negative integers. If a number k
at an index is positive, move forward k
steps. Conversely, if it’s negative, move backward k
steps. Since the array is circular, you may assume that the last element’s next element is the first element and the first element’s previous element is the last element.
Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be entirely in a single direction (forward or backward).
Return true
if there is a loop in the array, otherwise, return false
.
tortoise and hare
approach to detect cycles.public class Solution {
public boolean circularArrayLoop(int[] nums) {
int n = nums.length;
// Function to get the next index in a circular manner.
int nextIndex(int[] nums, int currentIndex) {
int n = nums.length;
int next = (currentIndex + nums[currentIndex]) % n;
if (next < 0) next += n;
return next;
}
for (int i = 0; i < n; i++) {
if (nums[i] == 0) continue; // Already visited or part of a 0-length loop.
// Start exploration from index i.
int slow = i, fast = i;
boolean isForward = nums[i] > 0; // Direction.
// Explore until we find a loop or confirm no loop exists.
while (true) {
slow = nextIndex(nums, slow);
fast = nextIndex(nums, fast);
if (isForward != (nums[fast] > 0)) break;
fast = nextIndex(nums, fast);
if (isForward != (nums[fast] > 0)) break;
if (slow == fast) {
if (slow == nextIndex(nums, slow)) {
break; // Single-element loop.
}
return true; // Valid loop found.
}
}
// Mark visited elements in the current direction.
slow = i;
while (nums[slow] != 0) {
int temp = slow;
slow = nextIndex(nums, slow);
nums[temp] = 0;
}
}
return false;
}
}
This algorithm combines cycle detection using the Floyd’s Tortoise and Hare approach with direction and visited checking. It efficiently handles the complexity of circular and directional array navigation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?