Circular Array Loop LeetCode solution in C++

1
class Solution {
2
public:
3
int next(vector<int> &nums, int i) {
4
int n = nums.size();
5
return (n + nums[i] + i) % n;
6
}
7

8
bool circularArrayLoop(vector<int> &nums) {
9
int n = nums.size();
10
// we can use slow and fast pointer to check whether there is loop or not
11
for (int &num : nums) num %= n;
12
for (int i = 0; i < n; i++) {
13
int slow = i, fast = i;
14
while (nums[slow] * nums[next(nums, fast)] > 0 &&
15
nums[slow] * nums[next(nums, next(nums, fast))] > 0) {
16
slow = next(nums, slow);
17
fast = next(nums, next(nums, fast));
18
if (slow == fast) {
19
if (slow == next(nums, slow)) // single length
20
return false;
21
return true;
22
}
23
}
24
/// DONOT TRAVERSE WHERE THERE IS NO PATH TO GET LOOP.
25
int j = i;
26
int val = nums[i];
27
while (nums[j] * val > 0) {
28
int nexx = next(nums, j);
29
nums[j] = 0;
30
j = nexx;
31
}
32
}
33

34
return false;
35
}
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0