Algorithms and Data Structures · Middle · Question 24 of 75

How do you detect a cycle in a linked list with O(1) extra memory?

Explanation

This is Floyd's "tortoise and hare" algorithm. If there's a cycle, the fast pointer eventually laps the slow one; if not, it reaches null. A Set also works but takes O(n) memory.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 24

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz