Untitled
unknown
plain_text
a year ago
1.9 kB
5
Indexable
public class ArrayCycleLength {
public static int findCycleLength(int[] arr) {
if (arr.length <= 1) {
return 0;
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) continue; // Skip visited elements
int slow, fast;
slow = fast = i;
boolean ifForward = arr[i] > 0;
// Step 1: Detect Cycle
while (true) {
slow = getNextPosition(arr, slow, ifForward);
if (slow == -1) break;
fast = getNextPosition(arr, fast, ifForward);
if (fast == -1) break;
fast = getNextPosition(arr, fast, ifForward);
if (fast == -1) break;
if (slow == fast) {
// Step 2: Find cycle length
return calculateCycleLength(arr, slow);
}
}
}
return 0; // No cycle found
}
// Step 2: Function to calculate the length of the cycle
private static int calculateCycleLength(int[] arr, int start) {
int count = 1;
int current = getNextPosition(arr, start, arr[start] > 0);
while (current != start) {
count++;
current = getNextPosition(arr, current, arr[start] > 0);
}
return count;
}
// Helper function to get next index
private static int getNextPosition(int[] arr, int index, boolean ifForward) {
boolean direction = arr[index] >= 0;
if (direction != ifForward) {
return -1;
}
int nextIndex = (index + arr[index]) % arr.length;
if (nextIndex < 0) {
nextIndex += arr.length;
}
if (nextIndex == index) {
return -1;
}
return nextIndex;
}
public static void main(String[] args) {
int[] arr = {2, -1, 1, 2, 2};
System.out.println("Cycle Length: " + findCycleLength(arr)); // Output: 3
int[] arr2 = {-1, -2, -3, -4, -5, 6};
System.out.println("Cycle Length: " + findCycleLength(arr2)); // Output: 0 (No cycle)
}
}
Editor is loading...
Leave a Comment