0

I am thinking about the problem of detecting cycles in lisp lists (based on cons cells). Traditional cycle detection algorithms like Floyd's (Tortoise and hare) or Brent's algorithm all assume that there is only a single "next" function. However with cons cells there are two possible next nodes (car or cdr). This means that most cycle detection algorithms can't be applied (at least I think they can't?). The only solution I have found for this is DFS with backlink tracking. Compared to Floyd's algorithm which only uses 2 pointers and a single compare per cycle, using a a full DFS could require the entire dataset to be inserted into a hashtable and requires a hash lookup every iteration. I am looking to see if there are algorithms that does not require O(n) space like DFS, but can still handle detecting cycles in list.

I know this is not a novel problem, because lisp systems have been around forever. This is something they have to deal with whenever they print an object. And it's not only applicable to lisp, but really any graph where nodes can have more then 1 "next". How is this solved in practice?

2
  • 2
    The "hash table" (may be just an array in case your graph nodes are enumerated, or an additional field in your graph nodes for remembering the traversal state) is the approach I've always used for this. It has the same asymptotic linear runtime as Floyd's "tortoise and hare" and only requires linear extra space (usually not an issue). I'm not aware of a way of finding cycles in digraphs that has sub-linear space complexity yet achieves linear time complexity; nested lists (what you call "lisp lists") are effectively equivalent to digraphs. Commented Nov 2, 2023 at 18:52
  • (as such, I believe this question is effectively a duplicate of Best algorithm for detecting cycles in a directed graph [closed]) Commented Nov 2, 2023 at 18:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.