Circular Array Loop LeetCode solution in Java

1
class Solution {
2
public boolean circularArrayLoop(int[] nums) {
3
for (int i = 0; i < nums.length; i++) {
4
boolean isForward = nums[i] > 0;
5
int slow = i;
6
int fast = i;
7
do {
8
slow = findNextIndex(nums, isForward, slow);
9
fast = findNextIndex(nums, isForward, fast);
10
if (fast != -1) {
11
fast = findNextIndex(nums, isForward, fast);
12
}
13
} while (slow != -1 && fast != -1 && slow != fast);
14
if (slow != -1 && slow == fast) {
15
return true;
16
}
17
}
18
return false;
19
}
20

21
private int findNextIndex(int[] arr, boolean isForward, int currentIndex) {
22
boolean direction = arr[currentIndex] >= 0;
23
if (isForward != direction) {
24
return -1;
25
}
26
int nextIndex = (currentIndex + arr[currentIndex]) % arr.length;
27
if (nextIndex < 0) {
28
nextIndex += arr.length;
29
}
30
if (nextIndex == currentIndex) {
31
nextIndex = -1;
32
}
33
return nextIndex;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0