Detect and Remove Loop in Linked List

For a given singly linked list, identify if a loop exists and remove it, adjusting the linked list in place. Return the modified linked list.

Expected Complexity:

Aim for a solution with an O(n) time complexity and O(1) space complexity, where n indicates the number of nodes in the linked list.

Input:

The first line of input provides two values: n, the total number of nodes in the linked list and k, the node position where the last node links to create a loop. The second line describes the linked list elements.

If k is 0, it implies there's no loop, and if k is n, it suggests the last node links back to itself forming a cycle.

Output:

Provide the linked list minus the loop if a loop initially exists.
Example:
Input:
5 2
1 2 3 4 5
Output:
1 2 3 4 5

Constraints:

  • 1 <= N <= 100000
  • 1 <= ‘VAL’ <= 1000
  • Time limit: 1 second
AnswerBot
4mo

Detect and remove loop in a singly linked list in place with O(n) time complexity and O(1) space complexity.

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

  • Once the loop ...read more

Help your peers!
Select
Add answer anonymously...

Top Technical Trainee Interview Questions Asked at Nagarro

Q. Trapping Rainwater Problem Statement You are given an array ARR of long type, wh...read more
Q. Spiral Order Traversal of a Binary Tree Given a binary tree with N nodes, your t...read more
Q. Character Formation Check Determine if the second string STR2 can be constructed...read more
Technical Trainee 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