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...

AlphaSense Software Developer interview questions & answers

A Software Developer was asked 11mo agoQ. Write a program to print the last 10 lines of a file, and configure it to run ev...read more
A Software Developer was asked 11mo agoQ. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
A Software Developer was asked Q. What is a peer-to-peer connection?

Popular interview questions of Software Developer

A Software Developer was asked 11mo agoQ1. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
A Software Developer was asked Q2. What is a peer-to-peer connection?
A Software Developer was asked Q3. Median of Two Sorted Arrays Given two sorted arrays A and B of sizes N and M, fi...read more
AlphaSense 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