Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Remove Loop From Linked List Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Remove Loop From Linked List

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

Given a linked list, remove the loop if it exists. 

You need to find the last node of the list that points to one of its previous nodes and make it point to NULL.

Approach

  • Let's say that the cyclic part of the list has length x and the non-cyclic part has length y.
  • Let's define two pointers to traverse the list, slowPtr and fastPtr, where slowPtr moves one node at a time and fastPtr moves two nodes at a time. If the list contains a loop then both the pointers must meet at a node inside the loop. Let's say this node is at a distance d from the start node of the loop.
  • When both the pointers point at the same node, it will give us:

        y + rf  * x + d = 2 *(y + rs * x +d)

        i,e y + d = (rf - 2*rs ) * x    

        where rf is the number of complete cycles by fastPtr and rs is the number of complete cycles by slowPtr.

  • From the above equation, it can be concluded that y+dis a multiple of x.
  • Set the slowPtr to the start of the list and now move both the pointers one node at a time. The node at which they meet will be the start of the loop. So set the next pointer of the previous node of fastPtr to NULL.

Analysis

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

Implementation

C++
/* This is the ListNode class definition

class ListNode {
public:
	int data;
	ListNode* next;

	ListNode(int data) {
		this->data = data;
		this->next = NULL;
	}
};
*/

void removeLoop(ListNode* list) {
    if (list == NULL || list->next == NULL) {
		return;
	}
	ListNode *slowPtr = list->next, *fastPtr = list->next->next;
	ListNode *prevNode = list->next;
	while (fastPtr != NULL && fastPtr->next != NULL) {
		if(slowPtr == fastPtr) {
			slowPtr = list;
			break;
		}
		slowPtr = slowPtr->next;
		prevNode = fastPtr->next;
		fastPtr = fastPtr->next->next;
	}
	if (fastPtr == NULL || fastPtr->next == NULL) {
		return;
	}
	while (slowPtr != fastPtr) {
		prevNode = fastPtr;
		slowPtr = slowPtr->next;
		fastPtr = fastPtr->next;
	}
	prevNode->next = NULL;
	return;
}
Java
/** This is the ListNode class definition

class ListNode {
	int data;
	ListNode next;

	ListNode(int data) {
		this.data = data;
		this.next = null;
	}
}
**/
	
class Solution {
	void removeLoop(ListNode list) {
	    if (list == null || list.next == null) {
			return;
		}
		ListNode slowPtr = list.next, fastPtr = list.next.next;
		ListNode prevNode = list.next;
		while (fastPtr != null && fastPtr.next != null) {
			if(slowPtr == fastPtr) {
				slowPtr = list;
				break;
			}
			slowPtr = slowPtr.next;
			prevNode = fastPtr.next;
			fastPtr = fastPtr.next.next;
		}
		if (fastPtr == null || fastPtr.next == null) {
			return;
		}
		while (slowPtr != fastPtr) {
			prevNode = fastPtr;
			slowPtr = slowPtr.next;
			fastPtr = fastPtr.next;
		}
		prevNode.next = null;
		return;
	}
}

Another Approach

The idea is to hash every node address that is encountered while traversing the linked list using a hashmap and if a node address is encountered again then that specific node is the start of the loop. So set the next pointer of the previous node to NULL.

Analysis

  • Time Complexity: O(n)
  • Auxiliary Space Complexity: O(n)

Implementation

C++
/* This is the ListNode class definition

class ListNode {
public:
	int data;
	ListNode* next;

	ListNode(int data) {
		this->data = data;
		this->next = NULL;
	}
};
*/

void removeLoop(ListNode* list) {
    unordered_map<ListNode*, int> visitedNodes;
	ListNode* currentNode = list;
	ListNode* prevNode;
	while(currentNode != NULL) {
		if (visitedNodes[currentNode] == 0) {
			visitedNodes[currentNode] = 1;
		} else {
			prevNode->next = NULL;
			break;
		}
		prevNode = currentNode;
		currentNode = currentNode->next;
	}
}
Java
/** This is the ListNode class definition

class ListNode {
	int data;
	ListNode next;

	ListNode(int data) {
		this.data = data;
		this.next = null;
	}
}
**/
	
class Solution {
	void removeLoop(ListNode list) {
	    HashMap<ListNode, Integer> visitedNodes = new HashMap<ListNode, Integer> ();
		ListNode currentNode = list;
		ListNode prevNode = null;
		while(currentNode != null) {
			if (visitedNodes.get(currentNode) == null) {
				visitedNodes.put(currentNode, 1);
			} else {
				prevNode.next = null;
				break;
			}
			prevNode = currentNode;
			currentNode = currentNode.next;
		}
		return;
	}
}
Related Content
Add Element at Kth Position in Linked List
Add Two Numbers as Lists
Add One to Linked List
Append Linked Lists
Clone List with Random Pointer
Remove Element at Kth Position in Linked List
Delete Node From Linked List
Delete Xth Node From End of Linked List
Detect Loop in Linked List
Find xth Node from End of Linked List
Flatten a Multi-Level Linked List
Insertion Sort Linked List
Intersection of Two Linked Lists
Kth Element in Linked List
Linked List Palindrome
Linked List to Array
Merge Sort Linked List
Merge Two Sorted Linked List
Middle Element of Linked List
Partition List
Print Linked List
Print Reversed Linked List
Remove Duplicates from Sorted Linked List
Remove Duplicates from Sorted Linked List - II
Remove occurrences in Linked List
Reorder List
Reverse a Linked List
Reverse a Linked List II
Reverse a Linked List in k-groups
Rotate a Linked List
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet