Find Nth Node from End of the Singly linked list.

Given N size node in the Singly Linked list and you have to find the kth node's value from the end. 
Suppose, You have been provided the above Singly Linked List and the interviewer asks you to return 2nd last element from the linked list. Your response will be 7 and if the kth element is greater than the size of the Linked list then return -1. -1 will represent that the kth element is not present.

This problem is repeatedly asked by many of the product based companies and the interviewer will grill you on it. He will add some constraint on the fly and asks you to solve it optimize way.
Suppose, If we are going to solve this problem what would be the solution that comes into our mind. A Singly linked list holds the count of the node in the size variable, We will iterate from the head node to size - kth node and return the kth node's value. Once you give this solution to the interviewer, he/she will directly tell you that there is no size variable available in this custom Singly linked list. 
We are now trying to solve it by using a dynamic array and store each node value in a particular index. We can directly fetch the value with the help of the array's index and return the result. Once you give this solution to the interviewer, he/she will ask you to write a solution without any extra space.
We are puzzled sometimes because of the interview pressure and solution doesn't hit at the right time. We can do this with the help of the two pointers/references of a Linked List class. The first reference will move k time and then they move together. When the first reference reaches at the end of the node and the second reference is exactly on the kth node. That's how we do it. 
public int get(Node head, int n) {
if (head == null)
return -1;
Node ref = head, fastRef = head;
while (n-- > 0){
if (fastRef == null)
return -1;
else
fastRef = fastRef.next;
}
while (fastRef != null) {
ref = ref.next;
fastRef = fastRef.next;
}
return ref.value;
}
I hope you understood the solution to the given problem. We will come up with a new challenge soon.

Comments

Popular posts from this blog

Recursion

Priority Queue