How can we find the starting node of a loop in link list?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In computer science and programming, a linked list is a linear collection of data elements, in which the order is not given by their physical placement in memory. Instead, each element points to the next. A more advanced problem you might encounter while working with linked lists is identifying a loop or cycle within the list and finding the node at which it starts. Here's how you can accomplish that task, complete with explanations and an example.
Detecting and Locating the Starting Node of a Loop
To detect the starting node of a loop (if a loop exists), you can use an ingenious solution known as Floyd's Cycle-Finding Algorithm or the Tortoise and Hare Algorithm. The approach involves two pointers moving at different speeds through the linked list.
Algorithm Steps
- Initialize Pointers:
- Take two pointers, `slow` and `fast`.
- `slow` moves by one step at a time, whereas `fast` moves by two steps.
- Detect Loop:
- Traverse the linked list using the two pointers.
- If there is no loop, `fast` will reach the end of the list (i.e., `fast` or `fast.next` will become `null`).
- If there is a loop, `slow` and `fast` will meet at some point inside the loop.
- Find Start of Loop:
- Once `slow` and `fast` meet, set one pointer to the head of the linked list and leave the other at the meeting point.
- Move both pointers one step at a time.
- The point at which they meet again is the starting node of the loop.
Technical Explanation
- Time Complexity:
- The algorithm runs in time complexity, where is the total number of nodes in the list (including nodes inside and outside the loop).
- Space Complexity:
- The algorithm uses space since it only requires a constant amount of additional memory.
Example
Consider the following linked list with nodes and a loop:
1 -> 2 -> 3 -> 4 -> 5
8 <- 7 <- 6
- Initialize `slow` and `fast` at node 1.
- Move `slow` one step and `fast` two steps until they meet. When `slow` is at node 7 and `fast` is at node 4, they will meet.
- Reset `slow` to the head (node 1), and traverse both pointers one step at a time.
- They will meet at node 3, which is the starting point of the loop.
- Use Cases: This algorithm is particularly beneficial for detecting-loop problems typical in interview environments or real-time applications like network routing.
- Limitations: If used on doubly linked lists or lists with multiple loops, modifications are necessary.
- Edge Cases: Handle linked lists with no nodes or a single node separately, as no loops can exist in these structures.

