You are given the head of a singly linked list and an integer n. Your task is to find and return the value of the nth node from the end of the linked list. If n is greater than the length of the linked list, return -1.
Example 1
Input: head = [1,2,3,4,5], n = 2
Output: 4
Explanation: The 2nd node from the end of the linked list is 4.
Example 2
Input: head = [10,20,30], n = 3
Output: 10
Explanation: The 3rd node from the end is the first node of the linked list, which is 10.
Example 3
Input: head = [5,10,15], n = 4
Output: -1
Explanation: The linked list contains only 3 nodes, so the 4th node from the end does not exist. Hence, the output is -1.
Sign in to write, run, and submit your solution against the full test suite.