• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Find loop in Singly linked list

February 20, 2014 by Dhaval Dave

There are several ways to find loop in singly linked list,

Loop Node5 Next pointer is point to Node3 in Singly Linked List

1 ---- 2 ---- 3 ---- 4 ---- 5
              |_____________|
  • Hashmap
  • Floyd’s cycle detection Algorithm
  • Fast and Slow pointer


Hash Map Method

  1. Start Traversing Linked List
  2. Repeat 3, 4 untill LinkedList’s end
  3. Search current node’s address in HashMap, if its not there :
    Push current node’s address to Hash
    else If current node’s address is  found in HashMap :
    LinkedList contains loop,
  4. Come out of loop

Floyd’s Cycle Algorithm : This method is also dependent on Floyd’s Cycle detection algorithm.

1) Detect Loop using Floyd’s Cycle detection algo and get the pointer to a loop node.
2) Count the number of nodes in loop. Let the count be k.
3) Fix one pointer to the head and another to kth node from head.
4) Move both pointers at the same pace, they will meet at loop starting node.
5) Get pointer to the last node of loop and make next of it as NULL.

 Fast And Slow Pointer Method : There is another way is with fast and slow pointer ,
 Logic of Algorithm :
Say Two runner are running in circular field, One runner say RunnerA runs with 10KMPH ‘s speed and one say RunnerB with 15KMPH (faster than first RunnerA), in circular path after some N rounds RunnerB will sure overtake (cross) RunnerA (means they will meet).
Same logic we are using to find loop with fast pointer and slow pointer, if they meet then they are in circular path.

W’ll keep faster Pointer to move Two steps and slow as One step.

Once they meet, We need to find node which is causing Loop,
that we can find it with below logic.
as faster point is double as fast as slow pointer, When they meet, they will be equally far head and count of node in loop.
So Follow steps after we find loop.
  1.  Count the number of nodes in loop. Let the count be k.
  2. Fix one pointer to the head and another to kth node from head.
  3. Move both pointers at the same pace, they will meet at loop starting node.
  4. Get pointer to the last node of loop and make next of it as NULL.

Code is given below

struct node
{
    int data;
    struct node* next;
};
int detectLoop(struct node *list)
{
 struct node *slow_p = list, *fast_p = list;
 while (slow_p && fast_p && fast_p->next)
 {
 slow_p = slow_p->next;
 fast_p = fast_p->next->next;
 if (slow_p == fast_p) {
 return 1; //to indicate loop is there
 }
 return 0; //to indeciate that ther is no loop
 }
}
void removeLoop(struct node *loop_node, struct node *head)
{
    struct node *ptr1 = loop_node;
    struct node *ptr2 = loop_node;
 
    unsigned int k = 1, i;
    while (ptr1->next != ptr2)
    {
        ptr1 = ptr1->next;
        k++;
    }
 
    ptr1 = head;
 
    ptr2 = head;
    for (i = 0; i < k; i++)
      ptr2 = ptr2->next;
 
    while (ptr2 != ptr1)
    {
        ptr1 = ptr1->next;
        ptr2 = ptr2->next;
    }
 
    ptr2 = ptr2->next;
    while (ptr2->next != ptr1)
       ptr2 = ptr2->next;
 
    ptr2->next = NULL;
}

Method 2)

As we need to count the nodes in loop, it gives more cycles or iterations in given problem, We can think of solution where we don’t need to use K (number of nodes in Loop).

void detectAndRemoveLoop(Node *head)
{
    Node *slow = head;
    Node *fast = head->next;
 
    // Search for loop using slow and fast pointers
    while (fast && fast->next)
    {
        if (slow == fast)
            break;
        slow = slow->next;
        fast = fast->next->next;
    }
 
    /* If loop exists */
    if (slow == fast)
    {
        slow = head;
        while (slow != fast->next)
        {
            slow = slow->next;
            fast = fast->next;
        }
 
        /* since fast->next is the looping point */
         /* remove loop */
         fast->next = NULL;
    }
}

 

Similar Articles

Filed Under: Adobe Interview Questions, Amazon Interview Question, Hacker Earth Questions, Interview Questions, Microsoft Interview Questions, problem Tagged With: Linked List

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Doubly linked list

Find Nearest Minimum number in left side in O(n)

Top 10 Interviews Techniqes for Campus Interview in IIT NIT BITS for MTech

FizzBuzz Solution C C++

Diagonal Traversal of Binary Tree

VMWare Openings

Regular Expression Matching

robot standing at first cell of an M*N matrix. It can move only in two directions, right and down. In how many ways, it can reach to the last cell i.e. (M, N) Code it

HackeEarth Flipkart’s Drone

ADOBE Aptitude C Language Test

Given array of 0’s and 1’s. All 0’s are coming first followed by 1’s. find the position of first 1

Inorder and Preorder traversals of a Binary Tree given. Output the Postorder traversal of it.

Apriori algorithm C Code Data Mining

Binary Tree in Java

Get K Max and Delete K Max in stream of incoming integers

Amazon Interview Experience – SDE Chennai

Introduction To Number Theory ( Part 1 )

Print vertical sum of all the axis in the given binary tree

Stickler thief

Python String and numbers

Calculate price of parking from parking start end time prices

Common Ancestor in a Binary Tree or Binary Search Tree

Printing intermediate Integers between one element & next element of array

Edit Distance ( Dynamic Programming )

Find and print longest consecutive number sequence in a given sequence in O(n)

write a c program that given a set a of n numbers and another number x determines whether or not there exist two elements in s whose sum is exactly x

K’th Largest Element in BST when modification to BST is not allowed

Find the number ABCD such that when multipled by 4 gives DCBA.

Get Minimum element in O(1) from input numbers or Stack

Walmart Labs Interview Experience

Copyright © 2025 · Genesis Framework · WordPress · Log in