I am solving this problem, a part of the problem that is giving me troubles is formulated as follows:
a. Start from index i=0;
b. Jump to index i=A[i];
c. If the current index i is outside the valid bound of [0..N-1], print “Out” and stop;
d. Else if the current index i is index N-1, print “Done” and stop;
e1. Otherwise, repeat step b;
e2. If doing this leads to an infinite loop, print “Cyclic” and stop;
(all output are without the quotes)
arr is an array of non-negative integers:
let index = 0;
const seen = new Set([0]);
while (true) {
index = arr[index];
if (index > arr.length - 1) {
console.log("Out");
break;
}
if (index === arr.length - 1) {
console.log("Done");
break;
}
if (seen.has(index)) {
console.log("Cyclic");
break;
}
seen.add(index);
}
I am getting WA (Wrong Answer) on some hidden test cases, but I can't for the life of me come up with a failing test case.
1 2 3 4 5 0->Done1 2 3 4 6 0->Out1 0 0->Cyclic
Edit:
My C++ solution has exactly the same failed test cases, must really be something with my logic...