Detect Cycle in a Linked List - The Coding Shala

Home >> Interview Questions >> Detect Cycle in a Linked List

Detect Cycle in a Linked List

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where the tail connects to. If pos is -1, then there is no cycle in the linked list.



Example 1:
Linked List Cycle - The Coding Shala

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the second node.

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the first node.

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.



Detect Cycle in a Linked List Java Program

Approach:
We can do it using HashSet. we check in the linked list if the current element is visited or not, if not then we add it to the set else return true but this would take additional O(n) Space. 

The alternative we can use two pointers. One slow pointer and one fast. The slow pointer will move by 1 step, fast by 2 steps. If there is a cycle available in the linked list then the fast pointer will catch up the slow pointer otherwise it will reach the null(end).  

Java 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) {
        if(head == null) return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null){
            if(slow == fast) return true;
            if(fast.next == null) return false;
            slow = slow.next;
            fast = fast.next.next;
        }
        return false;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala