JP Morgan Interview Question
SDE-3sTeam: Release Mgmt
Country: India
Interview Type: In-Person
tortise heir algorithm,
You take two pointers pointing to head
slow_ptr and fast_ptr;
slow_ptr moves one step ahead
and fast ptr moves two steps
below is the function in c++
midwaylist(node *head)
{
node *slow_ptr=head;
node *fast_ptr=head;
while(fast_ptr->next!=NULL || fast_ptr!=NULL)
{
slow_ptr=slow_ptr->next;
fast_ptr=fast_ptr->next->next;
}
cout << "Mid value is " << slow_ptr->data << endl;
}
The brute technique is counting the elements, finding the position of the middle one, and iterating the list again until that element.
You may want to use the runner approximation here: you use two pointers for iterating the list, the normal one and the runner, for each iteration the normal one advances one position and the runner advances two. When the runner gets to the end of the list you are pointing to the middle element with the normal one.
- Anonymous May 19, 2016