0

I know that we can use two pointers and using cycle detection algorithm but last week in an interview I was asked to do the same by using O(N) space Complexity. How can proceed?

3
  • 2
    Tortoise and the Hare Algorithm Commented Jul 5, 2013 at 11:00
  • 3
    Your two pointer algorithm is O(1) space, so it is already O(N) space. Commented Jul 5, 2013 at 11:00
  • @TheodoreNorvell I was going to suggest the very same, but wasn't sure. Good to know I was right. Commented Jul 5, 2013 at 11:01

1 Answer 1

1

For detailed implementation, read this post(How to determine if a linked list has a cycle using only two memory locations).

Basically you maintain two pointers, both of which point at the head of the linked list initially. On each enumeration, advance the first pointer by one node and the other by two. If at some point these two pointers reach an identical node again, a cycle is detected.

I gather from your description that you do know this algorithm. If the space taken by the linked list itself is not considered, this one works in O(1) space. And even with that much space considered, it's still O(n). (If space complexity is the only concern, obviously worse algorithm exists.)

Sign up to request clarification or add additional context in comments.

Comments

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.