Find First Node of Loop in Linked List
Last Updated :
11 Jul, 2025
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1.
Example:
Input:
Output: 3
Explanation: We can see that there exists a loop in the given linked list and the first node of the loop is 3.
Input:
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.
C++
// C++ program to find starting node
// of loop using Hasing
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to detect a loop in the linked list and
// return the node where the cycle starts using HashSet
Node* findFirstNode(Node* head) {
// HashSet to store visited nodes
unordered_set<Node*> st;
Node* currNode = head;
// Traverse the linked list
while (currNode != nullptr) {
// If the current node is already in the HashSet,
// then this is the starting node of the loop
if (st.find(currNode) != st.end()) {
return currNode;
}
// If not, add the current node to the HashSet
st.insert(currNode);
// Move to the next node
currNode = currNode->next;
}
// If no loop found, return nullptr
return nullptr;
}
int main() {
// Create a linked list: 10 -> 15 -> 4 -> 20
Node* head = new Node(10);
head->next = new Node(15);
head->next->next = new Node(4);
head->next->next->next = new Node(20);
head->next->next->next->next = head;
Node* loopNode = findFirstNode(head);
if (loopNode)
cout << loopNode->data;
else
cout << -1;
return 0;
}
Java
// Java program to find starting node
// of loop using Hasing
import java.util.HashSet;
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
// Function to detect a loop in the linked list and
// return the node where the cycle starts using HashSet
class GfG {
static Node findFirstNode(Node head) {
// HashSet to store visited nodes
HashSet<Node> st = new HashSet<>();
Node currNode = head;
// Traverse the linked list
while (currNode != null) {
// If the current node is already in the HashSet,
// then this is the starting node of the loop
if (st.contains(currNode)) {
return currNode;
}
// If not, add the current node to the HashSet
st.add(currNode);
// Move to the next node
currNode = currNode.next;
}
// If no loop found, return null
return null;
}
public static void main(String[] args) {
// Create a linked list: 10 -> 15 -> 4 -> 20
Node head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
head.next.next.next.next = head;
Node loopNode = findFirstNode(head);
if (loopNode != null)
System.out.println(loopNode.data);
else
System.out.println(-1);
}
}
Python
# Python program to find starting node
# of loop using Hasing
class Node:
def __init__(self, x):
self.data = x
self.next = None
# Function to detect a loop in the linked list and
# return the node where the cycle starts using HashSet
def findFirstNode(head):
# HashSet to store visited nodes
st = set()
currNode = head
# Traverse the linked list
while currNode is not None:
# If the current node is already in the HashSet,
# then this is the starting node of the loop
if currNode in st:
return currNode
# If not, add the current node to the HashSet
st.add(currNode)
# Move to the next node
currNode = currNode.next
# If no loop found, return None
return None
if __name__ == "__main__":
# Create a linked list: 10 -> 15 -> 4 -> 20
head = Node(10)
head.next = Node(15)
head.next.next = Node(4)
head.next.next.next = Node(20)
head.next.next.next.next = head
loopNode = findFirstNode(head)
if loopNode:
print(loopNode.data)
else:
print(-1)
C#
// C# program to find starting node
// of loop using Hasing
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to detect a loop in the linked list and
// return the node where the cycle starts using HashSet
static Node findFirstNode(Node head) {
// HashSet to store visited nodes
HashSet<Node> st = new HashSet<Node>();
Node currNode = head;
// Traverse the linked list
while (currNode != null) {
// If the current node is already in the HashSet,
// then this is the starting node of the loop
if (st.Contains(currNode)) {
return currNode;
}
// If not, add the current node to the HashSet
st.Add(currNode);
// Move to the next node
currNode = currNode.next;
}
// If no loop found, return null
return null;
}
static void Main() {
// Create a linked list: 10 -> 15 -> 4 -> 20
Node head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
head.next.next.next.next = head;
Node loopNode = findFirstNode(head);
if (loopNode != null)
Console.WriteLine(loopNode.data);
else
Console.WriteLine(-1);
}
}
JavaScript
// Javascript program to find starting node
// of loop using Hasing
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
// Function to detect a loop in the linked list and
// return the node where the cycle starts using HashSet
function findFirstNode(head) {
// HashSet to store visited nodes
let st = new Set();
let currNode = head;
// Traverse the linked list
while (currNode !== null) {
// If the current node is already in the HashSet,
// then this is the starting node of the loop
if (st.has(currNode)) {
return currNode;
}
// If not, add the current node to the HashSet
st.add(currNode);
// Move to the next node
currNode = currNode.next;
}
// If no loop found, return null
return null;
}
// Create a linked list: 10 -> 15 -> 4 -> 20
let head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
head.next.next.next.next = head;
let loopNode = findFirstNode(head);
if (loopNode) {
console.log(loopNode.data);
} else {
console.log(-1);
}
[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.
Follow the steps below to solve the problem:
- Traverse linked list using two pointers (slow and fast).
- Move one pointer(slow) by one step ahead and another pointer(fast) by two steps ahead.
- If these pointers meet at the same node then there is a loop. If pointers do not meet then the linked list doesn’t have a loop.
Below is the illustration of above algorithm:
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.
Below is the illustration of above algorithm:
For more details about the working & proof of this algorithm, Please refer to this article, How does Floyd’s Algorithm works.
C++
// C++ program to return first node of loop.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to detect a loop in the linked list and
// return the node where the cycle starts using
// Floyd’s Cycle-Finding Algorithm
Node* findFirstNode(Node* head) {
// Initialize two pointers, slow and fast
Node* slow = head;
Node* fast = head;
// Traverse the list
while (fast != nullptr && fast->next != nullptr) {
// Move slow pointer by one step
slow = slow->next;
// Move fast pointer by two steps
fast = fast->next->next;
// Detect loop
if (slow == fast) {
// Move slow to head, keep fast at meeting point
slow = head;
// Move both one step at a time until they meet
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
// Return the meeting node, which
// is the start of the loop
return slow;
}
}
// No loop found
return nullptr;
}
int main() {
// Create a linked list: 10 -> 15 -> 4 -> 20
Node* head = new Node(10);
head->next = new Node(15);
head->next->next = new Node(4);
head->next->next->next = new Node(20);
head->next->next->next->next = head;
Node* loopNode = findFirstNode(head);
if (loopNode)
cout << loopNode->data;
else
cout << -1;
return 0;
}
C
// C++ program to return first node of loop.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to detect a loop in the linked list and
// return the node where the cycle starts
// using Floyd’s Cycle-Finding Algorithm
struct Node* findFirstNode(struct Node* head) {
struct Node* slow = head;
struct Node* fast = head;
// Traverse the list
while (fast != NULL && fast->next != NULL) {
// Move slow pointer by one step
slow = slow->next;
// Move fast pointer by two steps
fast = fast->next->next;
// Detect loop
if (slow == fast) {
// Move slow to head, keep fast at meeting point
slow = head;
// Move both one step at a time until they meet
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
// Return the meeting node, which is the
// start of the loop
return slow;
}
}
// No loop found
return NULL;
}
struct Node* createNode(int data) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main() {
// Create a linked list: 10 -> 15 -> 4 -> 20
struct Node* head = createNode(10);
head->next = createNode(15);
head->next->next = createNode(4);
head->next->next->next = createNode(20);
head->next->next->next->next = head;
struct Node* loopNode = findFirstNode(head);
if (loopNode)
printf("%d\n", loopNode->data);
else
printf(-1);
return 0;
}
Java
// Java program to return first node of loop.
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to detect a loop in the linked list and
// return the node where the cycle starts
// using Floyd’s Cycle-Finding Algorithm
static Node findFirstNode(Node head) {
// Initialize two pointers, slow and fast
Node slow = head;
Node fast = head;
// Traverse the list
while (fast != null && fast.next != null) {
// Move slow pointer by one step
slow = slow.next;
// Move fast pointer by two steps
fast = fast.next.next;
// Detect loop
if (slow == fast) {
// Move slow to head, keep fast at meeting point
slow = head;
// Move both one step at a time until they meet
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
// Return the meeting node, which is the
// start of the loop
return slow;
}
}
// No loop found
return null;
}
public static void main(String[] args) {
// Create a linked list: 10 -> 15 -> 4 -> 20
Node head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
head.next.next.next.next = head;
Node loopNode = findFirstNode(head);
if (loopNode != null)
System.out.println(loopNode.data);
else
System.out.println(-1);
}
}
Python
# Python3 program to return first node of loop.
class Node:
def __init__(self, x):
self.data = x
self.next = None
def findFirstNode(head):
# Initialize two pointers, slow and fast
slow = head
fast = head
# Traverse the list
while fast and fast.next:
# Move slow pointer by one step
slow = slow.next
# Move fast pointer by two steps
fast = fast.next.next
# Detect loop
if slow == fast:
# Move slow to head, keep
# fast at meeting point
slow = head
# Move both one step at a time until
# they meet
while slow != fast:
slow = slow.next
fast = fast.next
# Return the meeting node, which is the
# start of the loop
return slow
# No loop found
return None
# Create a linked list: 10 -> 15 -> 4 -> 20
head = Node(10)
head.next = Node(15)
head.next.next = Node(4)
head.next.next.next = Node(20)
head.next.next.next.next = head
loopNode = findFirstNode(head)
if loopNode:
print(loopNode.data)
else:
print(-1)
C#
// C# program to return first node of loop.
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to detect a loop in the linked list and
// return the node where the cycle starts
// using Floyd’s Cycle-Finding Algorithm
static Node findFirstNode(Node head) {
// Initialize two pointers, slow and fast
Node slow = head;
Node fast = head;
// Traverse the list
while (fast != null && fast.next != null) {
// Move slow pointer by one step
slow = slow.next;
// Move fast pointer by two steps
fast = fast.next.next;
// Detect loop
if (slow == fast) {
// Move slow to head, keep fast at meeting point
slow = head;
// Move both one step at a time until they meet
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
// Return the meeting node, which is the start
// of the loop
return slow;
}
}
// No loop found
return null;
}
static void Main() {
// Create a linked list: 10 -> 15 -> 4 -> 20
Node head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
head.next.next.next.next = head;
Node loopNode = findFirstNode(head);
if (loopNode != null)
Console.WriteLine(loopNode.data);
else
Console.WriteLine(-1);
}
}
JavaScript
// Javascript program to return
// first node of loop.
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
// Function to detect a loop in the linked list and
// return the node where the cycle starts
// using Floyd’s Cycle-Finding Algorithm
function findFirstNode(head) {
let slow = head;
let fast = head;
// Traverse the list
while (fast !== null && fast.next !== null) {
// Move slow pointer by one step
slow = slow.next;
// Move fast pointer by two steps
fast = fast.next.next;
// Detect loop
if (slow === fast) {
// Move slow to head, keep fast at meeting point
slow = head;
// Move both one step at a time until they meet
while (slow !== fast) {
slow = slow.next;
fast = fast.next;
}
// Return the meeting node, which is
// the start of the loop
return slow;
}
}
// No loop found
return null;
}
// Create a linked list: 10 -> 15 -> 4 -> 20
const head = new Node(10);
head.next = new Node(15);
head.next.next = new Node(4);
head.next.next.next = new Node(20);
head.next.next.next.next = head;
const loopNode = findFirstNode(head);
if (loopNode) {
console.log(loopNode.data);
} else {
console.log(-1);
}
Related articles:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem