Detect and Remove Loop
Given a singly linked list, you have to detect the loop and remove the loop from the linked list, if present. You have to make changes in the given linked list itself and return the updated linked list.
Expected Complexity: Try doing it in O(n) time complexity and O(1) space complexity. Here, n is the number of nodes in the linked list.
Input format:
The first line of input contains two values: the number of nodes in the linked list and the value of the kth node from which the last node connects to form the loop while the second line of input contains the given linked list.
The value of k should be greater than or equal to 0 and less than equal to n. For, k equal to 0, there is no loop present in the linked list and for k equal to n, the last node is connected to itself to form the cycle.
Output Format:
The only output line contains the linked list after removing the loop if present.
Constraints:
1 <= N <= 100000.
1 <= ‘VAL’ <= 1000 .
Time limit: 1 sec
CodingNinjas
author
2y
Fix algorithm to solve the problem. Its standard. Used 2 pointer approach (slow-fast)
CodingNinjas
author
2y
Outer And Inner Loop
We are going to have two loops outer-loop and inner-loop
- Maintain a count of the number of nodes visited in outer loop.
- For every node of the outer-loop, start the inner loop from t...read more
CodingNinjas
author
2y
Look Up Table Approach
We are going to maintain a lookup table(a Hashmap) that basically tells if we have already visited a node or not, during the course of traversal.
- Visit every node one by one, unti...read more
CodingNinjas
author
2y
Slow And Fast Pointer Approach
- The idea is to have 2 pointers: slow and fast. Slow pointer takes a single jump and corresponding to every jump slow pointer takes, fast pointer takes 2 jumps. If there e...read more
Add answer anonymously...
Top AlphaSense Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in AlphaSense Software Developer
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app