VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-first-node-of-loop-in-a-linked-list/

⇱ Find First Node of Loop in Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find First Node of Loop in Linked List

Last Updated : 28 Aug, 2025

Given the head of a linked list, determine the starting node of the loop if a cycle exists. A loop occurs when the last node points back to an earlier node in the list. If no loop is present, return -1.

Example: 

Input:

👁 1

Output: 3
Explanation: The linked list contains a loop, and the first node of the loop is 3.

Input:

👁 2-

Output: -1
Explanation: No loop exists in the above linked list. So the output is -1.

[Naive approach] Using Hashing - O(n) Time and O(n) Space

The idea is to start traversing the Linked List from head node and while traversing insert each node into the HashSet. If there is a loop present in the Linked List, there will be a node which will be already present in the hash set.

  • If there is a node which is already present in the HashSet, return the node value which represent the starting node of loop.
  • else, if there is no node which is already present in the HashSet , then return -1.

Output
3

[Expected Approach] Using Floyd's loop detection algorithm - O(n) Time and O(1) Space

This approach can be divided into two parts:

1. Detect Loop in Linked List using Floyd’s Cycle Detection Algorithm:

This idea is to use Floyd’s Cycle-Finding Algorithm to find a loop in a linked list. It uses two pointers slow and fast, fast pointer move two steps ahead and slow will move one step ahead at a time.

Illustration:

2. Find Starting node of Loop:

After detecting that the loop is present using above algorithm, to find the starting node of loop in linked list, we will reset the slow pointer to head node and fast pointer will remain at its position. Both slow and fast pointers move one step ahead until fast not equals to slow. The meeting point will be the Starting node of loop.

Illustration:

For more details about the working & proof of this algorithm, Please refer to this article, How does Floyd’s Algorithm works.


Output
3

Related articles:

Comment
Article Tags:
Article Tags: