I will talk about this with the fact that I am not fully aware of Big O Notation, so maybe my thinking about it does not work.
I accidentally searched for SO when I came across the issue of detecting infinite loops in Linked Lists. It pointed to an algorithm here known as Turtle and Rabbit.
class Node { Node next; } boolean isInInfiniteLoop(Node node) { if (node == null) { return false; } Node turtle = node; // slower moving node Node rabbit = node.next; // faster moving node while (rabbit != null) { if (rabbit.equals(turtle)) { // the faster moving node has caught up with the slower moving node return true; } else if (rabbit.next == null) { // reached the end of list return false; } else { turtle = turtle.next; rabbit = rabbit.next.next; } } // rabbit reached the end return false; }
In the article, he mentions that it is O (N). From what I understand, O (N) means that the speed of the algorithm grows linearly with respect to the number of elements in the list.
However, if I don’t look at something wrong, the rabbit variable always skips 1 node (so it’s “faster”), which means that it has the potential to skip the node turtle, thereby having the loop potential around an infinite loop of 1 or more times before it becomes the same node as the turtle, which will mean that the worst case scenario is not O (N).
Am I missing something? I think the optimization may be to check if there is rabbit.Next.Equals(turtle) , but since none of the comments indicate this, I wonder if I am missing something.
algorithm big-o
Kalldrexx
source share