Detect the first node of the loop

You have been given a singly linked list which may or may not contain a cycle. You are supposed to return the node where the cycle begins (if a cycle exists).

A cycle occurs when a node's next pointer points back to a previous node in the list. The linked list is no longer linear with a beginning and end—instead, it cycles through a loop of nodes.

Input Format :
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first line of each test case contains the elements of the singly linked list separated by a single space and terminated by -1 and hence -1 would never be a list element.

The second line contains the integer position "pos" which represents the position (0-indexed) in the linked list where the tail connects to. If "pos" is -1, then there is no cycle in the linked list.
Output Format :
For each test case, print the integer position “pos” which represents the position of (0-indexed) in the linked list which is the first node of the cycle. Print -1 if there is no cycle in the linked list.

Print the output of each test case in a separate line.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints :
0 <= T <= 50
-10^4 <= N <= 10^4
-1 <= pos < N
-10^9 <= data <= 10^9 and data != -1

Time Limit: 1 sec
Follow Up:
Can you do this in O(N) time and usingconstant space?
AnswerBot
1y

To detect the first node of a cycle in a singly linked list, we can use the Floyd's Tortoise and Hare algorithm.

  • Use two pointers, slow and fast, to traverse the linked list.

  • If there is a cycle, the fa...read more

CodingNinjas
author
2y
Outer And Inner Loop

The basic idea of this approach is to check each node as the starting point for the cycle.

Now consider the following steps:

  • We are going to have two loops outer-loop and inner-loop...read more
CodingNinjas
author
2y
Look-Up Table Approach

We are going to maintain a lookup table(a HashSet) that basically tells if we have already visited a node or not, during the course of traversal.

  • Visit every node one by one, unt...read more
CodingNinjas
author
2y
Slow And Fast Pointer Approach

The basic idea of this approach is to use the technique based on two-pointers (slow and fast). Slow pointer takes a single jump and corresponding to every jump slow pointers take, fast pointer takes two jumps. If there exists a cycle, both slow and fast pointers will reach the exact same node. If there is no cycle in the given linked list, then the fast pointer will reach the end of the linked list well before the slow pointer reaches the end or null.

 

To get the starting point of the loop we can start moving both pointers again at the same speed such that one pointer (say slow) begins from the head node of the linked list and other pointers (say fast) begins from the meeting point. This time both the pointers will necessarily meet at the starting point of the loop.

 

You can refer to this article for more details. -----/

 

Now consider the following steps:

  • Start traversing the linked list using two pointers (slow and fast). Here, the slow pointer will make a jump of one node and the fast pointer will make jumps of 2 nodes.
  • If both pointers meet at some node then,
    • Point the slow pointer to the head node and again start iterating (this time both pointers will make a jump of 1 node).
    • Keep moving the slow and the fast pointers unit both of them meet at a common node. This common node will be the starting node of the cycle.
  • If slow and fast pointers never meet i.e. the fast pointer reaches the end of the linked list then the loop doesn’t exist in the given linked list, hence we will return -1.
Space Complexity: O(1)Explanation:

O(1)

 

We are using constant extra space. Hence, the overall space complexity is O(1).

Time Complexity: O(n)Explanation:

O(N), where ‘N’ is the total number of nodes.

 

Since we are using a slow pointer to traverse the linked list and the slow pointer is guaranteed to travel no more than ‘N’ steps before the fast pointer either meets the slow pointer or reaches the end of the list. So, the overall time complexity will be O(N).


Java (SE 1.8)
/*
Time Complexity: O(N)
Space Complexity: O(1)
Where 'N' is the number of nodes in the linked list.

*/

public class Solution
{
public static Node firstNode(Node head)
{

if (head == null)
{
// Empty linked list.
return null;
}

// Slow Pointer - This will be incremented by 1 Nodes
Node slow = new Node(head.data);
slow.next = head.next;

// Fast Pointer - This will be incremented by 2 Nodes
Node fast = new Node(head.data);
fast.next = head.next;

do
{
if (fast != null && fast.next != null)
{
fast = fast.next.next;
} else
{
// Fast pointer reached the end of the list.
return null;
}

slow = slow.next;
} while (fast != slow);

slow = head;

// To track the position of node.
while (slow != fast)
{
slow = slow.next;
fast = fast.next;
}
return slow;
}
}

Python (3.5)
'''
Time Complexity: O(N)
Space Complexity: O(1)
Where 'N' is the number of nodes in the linked list.

'''

def firstNode(head):

if (head == None):

# Empty linked list.
return None

# Slow Pointer - This will be incremented by 1 Nodes
slow = head

# Fast Pointer - This will be incremented by 2 Nodes
fast = head

while (True):

if (fast and fast.next):
fast = fast.next.next

else:

# Fast pointer reached the end of the list.
return None
slow = slow.next
if (fast == slow):
break

slow = head

# To track the position of node.
while (slow != fast):
slow = slow.next
fast = fast.next

return slow

C++ (g++ 5.4)
/*
Time Complexity: O(N)
Space Complexity: O(1)
Where 'N' is the number of nodes in the linked list.

*/

Node *firstNode(Node *head)
{
if (head == NULL)
{
// Empty linked list.
return NULL;
}

// Slow Pointer - This will be incremented by 1 Nodes
Node *slow = head;

// Fast Pointer - This will be incremented by 2 Nodes
Node *fast = head;

do
{
if (fast && fast->next)
{
fast = fast->next->next;
}
else
{
// Fast pointer reached the end of the list.
return NULL;
}

slow = slow->next;
} while (fast != slow);

slow = head;

// To track the position of node.
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
Add answer anonymously...
Wells Fargo Program Associate 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
Get AmbitionBox app

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