
Asked in AlphaSense
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.

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
Top Software Developer Interview Questions Asked at AlphaSense
Interview Questions Asked to Software Developer at Other Companies
Top Skill-Based Questions for AlphaSense Software Developer


Reviews
Interviews
Salaries
Users

