Skip to content

Commit 4fec5f0

Browse files
authored
Create 457-circular-array-loop.js
1 parent 912b70d commit 4fec5f0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

457-circular-array-loop.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
const circularArrayLoop = function(nums) {
6+
let n = nums.length;
7+
for (let i = 0; i < n; i++) {
8+
if (nums[i] == 0) {
9+
continue;
10+
}
11+
let j = i, k = getIndex(i, nums);
12+
while (nums[k] * nums[i] > 0 && nums[getIndex(k, nums)] * nums[i] > 0) {
13+
if (j === k) {
14+
// check for loop with only one element
15+
if (j === getIndex(j, nums)) {
16+
break;
17+
}
18+
return true;
19+
}
20+
j = getIndex(j, nums);
21+
k = getIndex(getIndex(k, nums), nums);
22+
}
23+
// loop not found, set all element along the way to 0
24+
j = i;
25+
let val = nums[i];
26+
while (nums[j] * val > 0) {
27+
let next = getIndex(j, nums);
28+
nums[j] = 0;
29+
j = next;
30+
}
31+
}
32+
return false;
33+
};
34+
35+
36+
function getIndex(i, nums) {
37+
const n = nums.length;
38+
return i + nums[i] >= 0? (i + nums[i]) % n: n + ((i + nums[i]) % n);
39+
}

0 commit comments

Comments
 (0)