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
Be the first one to answer
Add answer anonymously...
Qualcomm Associate Technology 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