Java-Advance-Programs icon indicating copy to clipboard operation
Java-Advance-Programs copied to clipboard

Add: JAVA Program Detect and Remove Loop in Linked List (Floyd’s Cycle Detection)

Open abhinab18 opened this issue 1 year ago • 0 comments

This problem is frequently asked in coding interviews and will enhance the LinkedList folder with an important cycle-handling algorithm.

Details

Approach:

Use two pointers (slow and fast) to detect a cycle.

If they meet, a loop exists.

To remove the loop, find the starting node of the cycle and set the previous node’s next pointer to null.

Input Example:

1 → 2 → 3 → 4 → 5
↑ ↓
8 ← 6

Output Example:

1 → 2 → 3 → 4 → 5 → 6 → 8

(Loop removed, list becomes linear).

Complexity:

Time: O(n)

Space: O(1) (no extra space used).

File to Add

LinkedList/DetectAndRemoveLoop.java

abhinab18 avatar Oct 30 '25 16:10 abhinab18