Nth Node From End of Linked List

Easy
1997.

Nth Node From End of Linked List

Nth Node From End of Linked List is an easy coding problem on two pointers, asked in Amazon, Microsoft and Samsung interviews.

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 (the last node is the 1st from the end).

If the list has fewer than n nodes, return -1.

Example 1

Input
head = [1,2,3,4,5,6,7,8,9], n = 2
Output
8

Example 2

Input
head = [10,5,100,5], n = 5
Output
-1
Explanation
The list has only four nodes.

Example 3

Input
head = [4,7], n = 2
Output
4
Explanation
The 2nd node from the end of a two-node list is its head.

Constraints

  • 1 <= number of nodes <= 10^6
  • 1 <= Node.val <= 10^4
  • 1 <= n <= 10^6
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * Definition for singly-linked list (provided by the judge — do not redefine it):
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {number}
 */
var getNthFromLast = function(head, n) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Nth Node From End of Linked List — Problem & Solution

Nth Node From End of Linked List solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.

Nth Node From End of Linked List is an easy coding problem on two pointers, asked in Amazon, Microsoft and Samsung interviews.

  • Difficulty: Easy
  • Topics: Two Pointers
  • Asked at: Amazon, Microsoft, Samsung
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

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 (the last node is the 1st from the end).

If the list has fewer than n nodes, return -1.

Example 1

Input: head = [1,2,3,4,5,6,7,8,9], n = 2
Output: 8

Example 2

Input: head = [10,5,100,5], n = 5
Output: -1
Explanation: The list has only four nodes.

Example 3

Input: head = [4,7], n = 2
Output: 4
Explanation: The 2nd node from the end of a two-node list is its head.

Constraints

  • 1 <= number of nodes <= 10^6
  • 1 <= Node.val <= 10^4
  • 1 <= n <= 10^6

Hints for Nth Node From End of Linked List

  1. Hint 1

    Counting the nodes and walking length - n steps takes two passes.

  2. Hint 2

    For one pass, use two pointers that stay exactly n nodes apart.

  3. Hint 3

    Advance the first pointer n steps (if it falls off the list, return -1), then move both until the first one falls off; the second is on the answer.

How to solve Nth Node From End of Linked List

Keep a gap of n nodes between two pointers. When the leading pointer runs off the end, the trailing one is exactly n nodes before the end.

Approach

  1. Move lead forward n times from head; if it becomes null before finishing, the list is too short — return -1.
  2. Set trail = head.
  3. While lead is not null, advance both lead and trail by one.
  4. Return trail.val.

Why it works

After the first phase lead is n nodes ahead of trail, and moving both keeps that gap. When lead is past the last node (position L), trail is at position L - n, which is the n-th node from the end.

Complexity

  • Time — O(L)
  • Space — O(1)

Pitfalls

  • n equal to the length is valid and gives the head; only n > L returns -1.
  • Check for null on every step of the first phase, not just at the end.

Reference solution

Python

from typing import Optional

def getNthFromLast(head: Optional[ListNode], n: int) -> int:
    lead = head
    for _ in range(n):
        if lead is None:
            return -1
        lead = lead.next
    trail = head
    while lead:
        lead, trail = lead.next, trail.next
    return trail.val

Java

public static int getNthFromLast(ListNode head, int n) {
    ListNode lead = head;
    for (int i = 0; i < n; i++) {
        if (lead == null) return -1;
        lead = lead.next;
    }
    ListNode trail = head;
    while (lead != null) { lead = lead.next; trail = trail.next; }
    return trail.val;
}

C++

int getNthFromLast(ListNode* head, int n) {
    ListNode* lead = head;
    for (int i = 0; i < n; i++) {
        if (!lead) return -1;
        lead = lead->next;
    }
    ListNode* trail = head;
    while (lead) { lead = lead->next; trail = trail->next; }
    return trail->val;
}

JavaScript

var getNthFromLast = function(head, n) {
    var lead = head;
    for (var i = 0; i < n; i++) {
        if (lead === null) return -1;
        lead = lead.next;
    }
    var trail = head;
    while (lead !== null) { lead = lead.next; trail = trail.next; }
    return trail.val;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 165 two pointers problems · the whole catalogue

Learn the technique: Two Pointers Technique