## Question

Given a linked list, determine whether it contains a cycle.

eg.

1 2 3 |
1 -> 2 -> 3 -> 4 ^ | |_________| |

Once you think that you’ve solved the problem, click below to see the solution.

*As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.*

## Solution

How was that problem? You can check out the solution in the video below.

Here is the source code for the solution shown in the video (Github):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
private class Node{ int val; Node next; } // Algorithm using extra space. Mark visited nodes and check that you // only visit each node once. public boolean hasCycle(Node n) { HashSet<Node> visited = new HashSet<Node>(); for (Node curr = n; curr != null; curr = curr.next) { if (visited.contains(curr)) return true; visited.add(curr); } return false; } // Floyd's algorithm. Increment one pointer by one and the other by two. // If they are ever pointing to the same node, there is a cycle. // Explanation: https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work public boolean hasCycleFloyd(Node n) { if (n == null) return false; Node slow = n; Node fast = n.next; while (fast != null && fast.next != null) { if (fast == slow) return true; fast = fast.next.next; slow = slow.next; } return false; } |

Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.

### Get Free Stuff!

Sign up now and I'll send you weekly emails with more content like this.