Timer is Running

Given a linked list consisting of L nodes and given a number N. The task is to find the Nth node from the end of the linked list.

Example 1:

L = 9, N = 2
value[] = {1,2,3,4,5,6,7,8,9}
Output: 8
Explanation: In the first example, there
are 9 nodes in linked list and we need
to find 2nd node from end. 2nd node
from end os 8.  

Example 2:

L = 4, N = 5
value[] = {10,5,100,5}
Output: -1
Explanation: In the second example, there
are 4 nodes in the linked list and we
need to find 5th from the end. Since 'n'
is more than the number of nodes in the
linked list, the output is -1.

Your Task:
The task is to complete the function getNthFromLast() which takes two arguments: reference to head and N and you need to return Nth from the end or -1 in case node doesn't exist..

Try to solve in single traversal.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

1 <= T <= 200
1 <= L <= 103
1 <= N <= 103

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Amit Khandelwal, Harshit Sidhwa
Author: AdityaChatterjee

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.