JSFiddle - React, Tailwind, and code Playground

by aramk

JavaScript

function hasCycle(a) {
	const visited = new Set();
  let currIndex = 0;
  for (let i = 0; i < a.length; i++) {
  	currIndex = a[currIndex];
    if (visited.has(currIndex)) return true;
    visited.add(currIndex);
  }
	return false;
}

console.log(hasCycle([1, 2, 3, 4, 5, 3]));
console.log(hasCycle([1, 2, 3, 4, 5, 6]));