In this video, we explain how to detect the first node of a loop in a linked list. A loop in a linked list occurs when a node's next pointer points back to one of the previous nodes, creating a cycle. We present two methods to find the first node of the loop: Using Hashing and Floyd’s Cycle-Finding Algorithm. The Naive Approach uses a hash set to store visited nodes while traversing the list. If a node is encountered that already exists in the hash set, that node is the start of the loop. If no loop is detected, the function returns -1.
We also demonstrate the expected approach using Floyd’s Cycle-Finding Algorithm (Tortoise and Hare algorithm), which efficiently detects loops using two pointers, slow and fast. The slow pointer moves one step at a time, and the fast pointer moves two steps. If the two pointers meet, a loop is detected. To find the starting node of the loop, the slow pointer is reset to the head of the list, and both pointers move one step at a time until they meet again. The meeting point is the start of the loop. This approach uses O(n) time and O(1) space, making it highly efficient.
For more details, please go through - Find First Node of Loop in Linked List