1
var circularArrayLoop = function (nums) {2
// cannot be a cycle if there are less than 2 elements3
const numsLen = nums.length;4
if (numsLen < 2) return false;7
const visited = Array(numsLen).fill(false);9
// check each index to see if a cycle can be produced10
for (let i = 0; i < numsLen; i++) {11
if (visited[i]) continue;13
// determine initial direction14
const isPositive = nums[i] > 0;16
// reset which indices were visited after each iteration17
const visitedPerIdx = Array(numsLen).fill(false);19
// reset cycle length and current index after each iteration23
// loop while cycle is valid25
// break if current index moves cycle in opposite direction26
if (isPositive !== nums[currIdx] > 0) break;28
// calc next valid index29
let nextIdx = (currIdx + nums[currIdx]) % numsLen;30
// map negative index to a positive index31
if (nextIdx < 0) nextIdx += numsLen;33
// break if cycle points to same index34
if (currIdx === nextIdx) break;37
// a cycle is found when the index has already been visited in the current outer iteration, and38
// the cycle length is greater than 1.39
if (visitedPerIdx[nextIdx] && cycleLen > 1) return true;41
visitedPerIdx[nextIdx] = true;42
visited[nextIdx] = true;43
// set curr index to new index