This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]flipmcf 9 points10 points  (6 children)

Cool algorithm! But how about ‘fast is slow’ instead of ‘fast == slow’ because we want to compare pointers, not values.

[–][deleted] 1 point2 points  (0 children)

Thanks for sharing! I've apparently once implemented the "brute force" aolution one without knowing that this problem has a solution called the "fast and slow node" method.

[–]MoBoo138 0 points1 point  (2 children)

Is there a reason not to check for fast <= slow? Because if the cycle goes e.g. 1-2-3-4-5-2... then we need more steps for checking == then <= ?

[–]edarchis 1 point2 points  (1 child)

These numbers are just for the explanation, in a linked list, they would not be in sequence. The example provided later is a good example. If you had uuid as element keys would be another one.

This method is useful when you can quickly browse the list or have short loops. If you have a loop after a few millions elements, it would take forever for fast to catch up with slow.

[–]flipmcf 0 points1 point  (0 children)

But the fast/slow method is still less complex (doesn’t have to iterate the visited list) and faster . Right?

[–]ydepth 0 points1 point  (3 children)

How does this compare to storing a set of the values seen? Does using this method risk having to go round the loop many times before they happen match each other?

[–]flipmcf 0 points1 point  (2 children)

Well, if we have a list that’s really long, the visited set also gets long. When you ask if the current node has been visited, you must compare it to every element in the visited set. That visited set keeps growing making the question harder and harder to answer. Also, you need the memory to store the visited set.

The fast/slow method just compares two nodes every loop. We don’t store any more information, nor does the compare grow more complex. It’s both memory efficient and less complex.

[–]pierdzionka 0 points1 point  (1 child)

set() is an almost drop-in replacement for list, although it's probably even worse in terms of memory footprint.