Skip to content
Onsite

Nth Node from End

EasyP1Coding

Given the head of a singly linked list and an integer n, return the value of the n-th node counted from the end of the list (n = 1 is the last node). If the list has fewer than n nodes, return -1.

A list node has val and next. The ListNode class is already defined for you. Aim for a single pass over the list.

Example 1

Input
head = [1,2,3,4,5], n = 2
Output
4

Example 2

Input
head = [1,2,3,4,5], n = 5
Output
1

Example 3

Input
head = [7], n = 2
Output
-1

Constraints

  • 0 <= number of nodes <= 10^5
  • -10^5 <= Node.val <= 10^5
  • 1 <= n <= 10^5

Hints

Run checks the 3 visible tests, Submit all 9.