Find Nth to Last Element of Singly Linked List
Filed under Amazon
Free read 1 of 3Confirm 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
Confirm 1-based indexing for n (e.g., n=1 means the very last element).
Traverse the list completely to find its length L, then traverse a second time to the (L - n)th node.
Use two pointers. Advance the first pointer n steps ahead, then move both pointers together until the first pointer reaches the end.
Single-node list with n=1, or n equal to the exact total number of nodes.
Solution
O(L) time, O(1) space where L is list length
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.