Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Nth Node From End

Medium Acceptance 69.00% Points 30.00

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.

Hints
Hint 1
N/A
Constraints
  • 1 = Number of nodes = 105
  • -10? = Node.data = 10?
  • 1 = n = 105
Companies
Microsoft
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions