700332. Remove loop in Linked List

Medium

Remove Loop in Linked List

Summary

Given a linked list, remove the loop if it exists. The linked list can contain multiple nodes with duplicate values and the loop can start from any node.

This problem is about manipulating a linked list to detect and remove a loop that might be present in the list. The key concepts involved are traversing the linked list and using two pointers technique to detect the loop.

Detailed Explanation

The approach to solve this problem involves two-pointer technique, where we move one pointer faster than the other. If there is no loop, these two pointers will eventually meet at some node. However, if there is a loop, they will meet at some node within the loop. Once we detect the meeting point, we reset one of the pointers to the starting point and then move both pointers at the same speed. The meeting point of these two pointers would be the start of the loop.

Here's the step-by-step breakdown:

  1. Initialize two pointers slow and fast to the head of the linked list.
  2. Move the fast pointer one step at a time, while moving the slow pointer one step at a time.
  3. If there is no loop, fast will eventually meet slow.
  4. If there is a loop, fast and slow will meet within the loop.
  5. Reset slow to the starting point and move both slow and fast one step at a time.
  6. The meeting point of these two pointers would be the start of the loop.

Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public ListNode detectAndRemoveLoop(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }

    ListNode slow = head, fast = head;

    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;

        if (slow == fast) {
            break;
        }
    }

    if (fast == null || fast.next == null) {
        return head;
    }

    slow = head;
    while (slow.next != fast) {
        slow = slow.next;
        fast = fast.next;
    }

    slow.next = null;

    return head;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.