## Flipkart Interview Question

Site Reliability Engineers**Team:**GGn

**Country:**United States

**Interview Type:**In-Person

circular_LL(node *root){

p=root;

q=root;

do{

p=p->next;

q=q->next->next;

}while(p->data!=q->data && p!=null);

}

This code will show the meeting point and detects the circular linked list

Let each node contains a flag 'isVisited' which is set to 'False' initially..

while traversing the list modify the 'isVisited' variable to 'True' in each node....

when you find the node with 'isVisited' variable with 'True'.. then it is circularly linked list and this node is the meeting point.

1. take two pointers fast & slow.

2. Move slow once & fast twice until they do not meet or fast becomes NULL(No cycle)

3. Move slow to root & move slow & fast one step at a time until they do not meet. This is the start of the cycle. Here is pseudo code:

```
findCycle(root)
{
struct node* slow,*fast;
slow=fast=root;
while(fast && fast->next && fast!=slow)
{
fast=fast->next->next;
slow=slow->next;
}
if(!fast || !(fast->next)) return NULL;
slow=root;
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
return fast;
}
```

Fix fast at the meeting point, move slow to the root.

Now move both slow & fast once until they do not meet.

@shondik: Even I did not understand your 3rd point here. Consider a case where cycle exists for the entire linked list i.e., 1->2->3->4->1 (the first '1') then the fast and slow pointer will never meet and the last while loop will not come out.

Have two pointer which is pointed to head of the linked list initially.Then Increment the first pointer by 1, and increment the second pointer by 2 . If these 2 pointers then theres is a circle and meeting point is value to be print.

1. Take two pointers, fast and slow. At each iteration, the fast pointer moves forward two nodes and the slow pointer moves forward one node. If the two pointers meet, that means there is a loop. Break out of the loop.

2. Now start a counter to find out the length of the loop. Initialize the counter to 0. Don't move the slow pointer, only move the fast pointer forward. For every iteration, increment the counter by 1. When the slow and fast pointers meet, the counter's value will give you the length of the loop.

3. Now that you have the length of the loop (loopLength), initialize both slow and fast pointers to the head of the linked list. Start a for loop and move the fast pointer forward loopLength number of times. At this point, the slow pointer points to the head and the fast pointer is loopLength nodes ahead of the slow pointer.

4. Now just move the slow and fast pointers forward till they meet. Where they meet is the beginning of the loop.

- Bonzo July 08, 2012