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.

Be the first one to answer
Add answer anonymously...
AlphaSense Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter