This is similar to the case when you can finally apply this question about interview trivia: find the loop in a linked list using only O (1) memory.
In this case, your “linked list” is a sequence of elements that you list. Use two counters, start them at half speed, and if fast speed runs to slow, then you have a cycle. It will also be O (n), not O (n ^ 2), required to check the "noticed" list. The disadvantage is that you only learn about the loop after several processed nodes several times.
In this example, I replaced the half speed method with the simpler drop markers method.
class GenTreeNode { ...
Craig gidney
source share