โ† Amazon questions

Find Nth to Last Element of Singly Linked List

Filed under Amazon

Free read 1 of 3

Confirm 1-based indexing for n (e.g., n=1 means the very last element).

The question

Implement an algorithm to find the nth-to-last element of a singly linked list.

Constraints

  • n is guaranteed to be less than or equal to the length of the linked list.
  • 1 <= n <= length

Examples

Input
head = [1, 2, 3, 4, 5], n = 2
Output
4
Why
The 2nd element from the last is 4.

Approach

  1. Confirm 1-based indexing for n (e.g., n=1 means the very last element).

Solution

O(L) time, O(1) space where L is list length

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def nthToLast(self, head: ListNode, n: int) -> int:
        fast = slow = head
        for _ in range(n):
            fast = fast.next
        while fast:
            fast = fast.next
            slow = slow.next
        return slow.val

Tips

  • What they are testing: Test with n equal to 1 (last element) and n equal to the length of the list (first element).
  • Common mistake: Failing to handle off-by-one errors when advancing the pointer by n steps before starting the second pointer.

Related Amazon questions

Collected from public candidate posts and coding forums. Updated Nov 2026.