I don’t understand below code why the “Math.abs(nums[pointer] % nums.length) == 0” could verify it is not a cycle because I think [3,3,3] is also a cycle, is it correct by the statement of the problem?
I think this part of the function isNotCycle
does not correctly identify all valid cycles according to the problem statement. It’s an edge case that the current function would not handle correctly.
// A function to detect a cycle doesn’t exist
public static boolean isNotCycle(int[] nums, boolean prevDirection, int pointer) {
// Set current direction to true if current element is positive, set false otherwise.
boolean currDirection = nums[pointer] >= 0;
// If current direction and previous direction are different or moving a pointer takes back to the same value,
// then the cycle is not possible, we return true, otherwise return false.
if (prevDirection != currDirection || Math.abs(nums[pointer] % nums.length) == 0) {
return true;
}
return false;
}
Course: Grokking Coding Interview Patterns in Java - Learn Interactively
Lesson: Solution: Circular Array Loop - Grokking Coding Interview Patterns in Java