Loop Detection and Removal in Linked List

In a singly linked list, detect if a loop exists and remove the loop if present. Modify the linked list directly to eliminate any loops before returning it.

Input:

The first line of input specifies two values: the total number of nodes in the linked list and the index k, indicating the node to which the last node is connected to form a loop. The second line contains the linked list elements.

If k = 0, no loop exists. If k = n, the last node connects to itself forming a loop.

Output:

Return the linked list after removing any loop detected.

Example:

Given:
5 2
10 20 30 40 50
Output:
10 20 30 40 50
Explanation:

Initially, a loop is present by connecting node at index 4 (value 50) to node at index 2 (value 30). The modified linked list after removing the loop is 10->20->30->40->50.

Constraints:

  • 1 ≤ N ≤ 100000
  • 1 ≤ VAL ≤ 1000
  • Time limit: 1 second

Note:

Optimize to achieve O(n) time complexity with O(1) space complexity, where n is the number of nodes.

AnswerBot
4mo

Detect and remove loop in a singly linked list efficiently.

  • Use Floyd's Cycle Detection Algorithm to detect the loop in the linked list.

  • Once the loop is detected, use two pointers to find the start of ...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at AlphaSense

Q. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
Q. Write a program to print the last 10 lines of a file, and configure it to run ev...read more
Q. What are some key concepts related to virtual memory, and can you discuss any fo...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits