[LeetCode] Circular Array Loop

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, then move forward k steps. Conversely, if it’s negative (-k), 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 (or a cycle) in nums. A cycle must start and end at the same index and the cycle’s length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
bool circularArrayLoop(vector<int> &nums) {
int sz = nums.size(), g = 1;
vector<int> gr(nums.size(), 0);
for (int i = 0; i < sz; i++, g++) {
if (gr[i] || !(abs(nums[i]) % sz)) {
nums[i] = 0;
continue;
}

bool flag = nums[i] > 0;
int pos = i;
do {
int prev = pos;
pos += nums[pos];
nums[prev] = 0;
gr[prev] = g;
if (pos >= sz)
pos -= sz * (pos / sz);
else if (pos < 0)
pos += sz * ((-pos / sz) + 1);

if ((flag && nums[pos] < 0) || (!flag && nums[pos] > 0) || (nums[pos] && !(abs(nums[pos]) % sz)))
break;

if (gr[pos] == gr[i])
return true;

} while (nums[pos]);

}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/30/PS/LeetCode/circular-array-loop/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.