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 ListFinding 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
- Set two pointers, first and second, both at the head.
- Move first forward N steps.
- Now move first and second forward together, one step at a time.
- 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
- Move first ahead by 2: first is now at node 3
- Move both together: first=4, second=2
- Move both together: first=5, second=3
- Move both together: first=null, second=4
Output: 2nd from end = 4
Press ▶ Run to watch it step by step.
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]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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.