Question: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.



    Output: 0

    The easier method to find the cycle has been discussed in this post.

    This method is based upon the idea of a circular race track. If there is a slow runner and a fast runner, eventually the fast runner will catch up the slow runner from behind. A similar analogy can be applied to a tortoise and a hare and hence the method is also called Tortoise and Hare method or the Floyd-Warshal algorithm.

    The method is divided into 2 steps.

    STEP 1: Determine if there is a loop.
    The first phase/step of this method is to determine if there is actually any loop in the Linked List. If no loop is found, then we need to directly return null.

    STEP 2: Find the loop.

    • We initialize 2 pointers. Fast(hare) and slow(tortoise).
    • Advance slow pointer by 1 step. Advance fast pointer by 2 steps.
    • Keep performing the above step in a loop until both the pointers meet.
    • As soon as they meet, start one more pointer from the beginning of the list.
    • Move the slow pointer and the new pointer one step at a time.
    • The place where they meet is the point where the loop starts in the linked list.

    To have a better understanding of why this method works, have a look at the following image.

    • Both hare and tortoise start from POINT 1.
    • The hare covers distance ‘F’ enters the loop and starts moving in the loop at POINT 2.
    • The hare runs for a while as he is fast and moves on path ‘a’.
    • The tortoise now enters the loop at POINT 2 after covering ‘F’ and keeps on moving on path ‘a’. While the hare is now on path ‘b’.
    • The tortoise keeps on moving on path ‘a’ and the hare eventually catches up with the tortoise at POINT 3.
    • Start a new pointer from POINT 1 and it runs at the same speed of tortoise.

    We know that speed of hare is double the speed of tortoise.
    Let us look at a little math now:-

    ​2 * distance(tortoise)​ ​​​​= distance(hare)​
    2 * (F + a) = F + a + b + a​
    ​2F + 2a = F + 2a + b
    ​F​ = b​​

    Hence POINT 2 is the point where loop starts.

    The source-code for the above algorithm is given below.

    // Template for a linked list node
    class ListNode {
        int value;
        ListNode next;
    }
    
    public class Solution {
    
        private ListNode getIntersect(ListNode head) {
            ListNode tortoise = head;
            ListNode hare = head;
    
            // A fast pointer will either loop around a cycle and meet the slow
            // pointer or reach the `null` at the end of a non-cyclic list.
            while (hare != null && hare.next != null) {
                tortoise = tortoise.next;
                hare = hare.next.next;
                if (tortoise == hare) {
                    return tortoise;
                }
            }
    
            return null;
        }
    
        public ListNode detectCycle(ListNode head) {
            if (head == null) {
                return null;
            }
    
            // If there is a cycle, the fast/slow pointers will intersect at some
            // node. Otherwise, there is no cycle, so we cannot find an entrance to
            // a cycle.
            ListNode intersect = getIntersect(head);
            if (intersect == null) {
                return null;
            }
    
            // To find the entrance to the cycle, we have two pointers traverse at
            // the same speed -- one from the front of the list, and the other from
            // the point of intersection.
            ListNode ptr1 = head;
            ListNode ptr2 = intersect;
            while (ptr1 != ptr2) {
                ptr1 = ptr1.next;
                ptr2 = ptr2.next;
            }
    
            return ptr1;
        }
    }
    Code language: Java (java)

    Time Complexity: O(n)
    Space Complexity: O(1)

    A sample problem can be found here.

    1 comment
    0 FacebookTwitterLinkedinWhatsappEmail
  • Linked List

    Find cycle in a linked list. (Method 1)

    by nikoo28
    3 minutes read

    Question: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Output: 0 We are given a linked list which may or may not have a loop. A loop in a linked list means that if we keep doing a next, we will never reach null. Thus, we can be clear of a fact that if we reach null, then the list does not have a loop. So how do we detect if there is a loop in the linked list. One…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    Next Greater Element in an array. [NGE]

    by nikoo28
    5 minutes read

    Question: There is an array A[N] of N numbers. You have to compose an array Output[N] such that each element in Output[i] will tell the next greater element to the right in the original array. If there is no greater number to the right, then the output array should contain -1 in that position.Array 1: {4, 6, 5, 4, 3, 4, 9, 8, 1} Output: {6, 9, 9, 9, 4, 9, -1, -1, -1} Let us try to understand the problem statement. We are given an input array that has…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an integer N, find all the prime factors of the number. Input: N = 45 Output: 3 5 Finding prime factors of any numbers is a very important concept in number theory. One sample problem is available here in which we have to find the largest prime factor. The mathematical concept behind this problem is simple. We start with ‘2’ and keep dividing the original number to get rid of composite factors. Continue this process until the number is no longer divisible by 2. This means that at…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an integer N, find the prime numbers in that range from 1 to N. Input: N = 25Output: 2, 3, 5, 7, 11, 13, 17, 19, 23 We have several ways of finding prime numbers. Some of the methods are discussed in the these posts. Method 1 Method 2 Method 3 In this post we will find the first N prime numbers using the Sieve of Eratosthenes. This technique is helpful in scenarios when we have to give immediate results and we need to query the prime numbers…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Find the sum of even Fibonacci numbers.

    by nikoo28
    3 minutes read

    Question: Find the sum of even fibonacci numbers upto a limit N. Input:100Output: 44 Fibonacci numbers are a miracle of Math and are defined as:- Thus the Fibonacci series can be given as0, 1, 1, 2, 3, 5, 8, 13, 21… Let us try to understand the question. We need to find all the Fibonacci numbers till a limit ‘N’ and then sum only the even numbers in them.Example:N = 10 Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8 Sum of even numbers: 2 + 8 = 10 N…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given two strings, determine if they share a common sub-string. If they have a common sub-string, print YES else print NO. Input:studyalgorithmsalgosOutput: YES This is one of the easy problems but can get a little tricky, if we do not understand it completely. Let us try to understand the test caseString 1 = “studyalgorithms” String 2 = “algos”The sub-string “algo” is common between both the sub-strings and therefore the answer is “YES“. Let us try to take one more test case. String 1 = “hello” String 2 = “world”The…

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More