Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Nth Node From End

Medium Acceptance 69% Points 30

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.

Examples
Example 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

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

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.

Constraints
  • 1 = Number of nodes = 105
  • -10? = Node.data = 10?
  • 1 = n = 105
Topics
Linked List
Companies
Microsoft
Added 25 Jul 2026 69% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5
2
4