Data Structures · Visualization

Linked List: Nth from End

Linked List

Finding the Nth node from the end in a single pass uses two pointers separated by a gap of N nodes. Time: O(n) (single pass). Space: O(1).

Big-O: Lookup O(n); insert/delete at head O(1).

Linked List: Nth from End

Linked List

Finding the Nth node from the end in a single pass uses two pointers separated by a gap of N nodes. Once the first pointer has moved N steps ahead, both pointers advance together; when the leading pointer hits the end, the trailing pointer is exactly N nodes from the end.

How Nth from End Works

  1. Set two pointers, first and second, both at the head.
  2. Move first forward N steps.
  3. Now move first and second forward together, one step at a time.
  4. When first reaches null, second is at the Nth node from the end.

Nth from End Worked Example

Input: Find 2nd from end in head -> 1 -> 2 -> 3 -> 4 -> 5 -> null

  1. Move first ahead by 2: first is now at node 3
  2. Move both together: first=4, second=2
  3. Move both together: first=5, second=3
  4. Move both together: first=null, second=4

Output: 2nd from end = 4

Try your own input
Linked List: Introduction
A chain of nodes, each holding a value plus a pointer to the next node — unlike an array, the values are not stored side by side in memory.
12
99
37
5
71
∅
Active / pointers Result null (end) Random pointer
Linked List: Introduction
Press ▶ Run to watch it step by step.
Python · Singly Linked List in Code
def nth_from_end(head, n):
    fast = slow = head
    for _ in range(n):       # advance fast by n
        fast = fast.next
    while fast:
        slow = slow.next     # keep gap of n
        fast = fast.next
    return slow.val

# one pass, O(n)
# example: nth from end 2 on [1, 2, 3, 4, 5]
Input: Find 2nd from end in head -> 1 -> 2 -> 3 -> 4 -> 5 -> null

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Nth from End Time & Space Complexity

TimeO(n) (single pass)
SpaceO(1)

When to Use Nth from End

  • Removing the Kth-to-last element in one pass (common interview problem)
  • Implementing 'last N items' features like recent history
  • Efficient list processing without first computing the total length

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.