## Problem:

Given a linked list and the head node of the linked list find if there is a loop / cycle in the linked list, that is if the tail node points back to any of the previous nodes.

For example:

The below linked list has a cycle:

Output is true for the above linked list.

Try out the solution here:

https://leetcode.com/problems/linked-list-cycle/

## Solution:

**Hint:**

- Have two pointers , a slow pointer moving one node at a time and a fast pointer moving two nodes at a time. If they meet each other there is a cycle.

## ALGORITHM:

**STEP 1:** Initialize two pointers , slow and fast pointing to the head

**STEP 2:** While the pointers are not null , increment slow pointer by one node and fast pointer by two nodes.

**STEP 2a:** If the pointers meet return true

**STEP 3:** Return false

## Code:

```
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next != null ){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
}
```

Time complexity is O(n) where n is the number of nodes.

There is no extra space required apart from storing the slow and fast pointers.

That’s it!

## Leave a Reply