Without marking nodes, find out if a linked list has a cycle in it or not.
💡Strategies for Solving This Problem
Classic Problem, Elegant Solution
Got this at Amazon. It's a standard problem but the solution (Floyd's Cycle Detection) is so clever that when you see it, it clicks forever.
The Insight
Imagine two runners on a circular track. If one runs twice as fast, they'll eventually lap the slower runner. Same idea with pointers in a linked list.
Floyd's Algorithm (Tortoise and Hare)
- Use two pointers: slow (moves 1 step) and fast (moves 2 steps)
- If there's a cycle, fast will eventually catch up to slow
- If there's no cycle, fast reaches the end (null)
This is O(n) time and O(1) space. You can't do better.
Alternative: Hash Set (Not Optimal)
Store visited nodes in a Set. If you see a node twice, there's a cycle. Works but uses O(n) space. My Amazon interviewer said "Can you do it without extra space?" - that's your cue for Floyd's.
Follow-Up Questions They'll Ask
- "Where does the cycle begin?" - This is the hard part. After detecting a cycle, there's a mathematical proof about where the entry point is.
- "What's the length of the cycle?" - Once pointers meet, count how many steps until they meet again.
I didn't know these follow-ups in my first Amazon interview. Study them.