Remove N-th Node From End

Two-pointer technique to remove nth node from end

Read Here
Step0 / 8
PhaseInitialize
Nodes5
N2
Target
Back To Linked List

Remove Nth From End (Python)

6 slow = dummy
8 # Move fast n steps ahead
......
10 fast = fast.next
11
12 # Move both until fast reaches end
......
14 slow = slow.next
15 fast = fast.next
16
......
18 slow.next = slow.next.next
19
20 return dummy.next
Current Line (7): Empty line

Remove Nth From End

INITIALIZE

Step

0 / 8

Phase

Initialize

N

2

Target

null1next2next3next4next5nextfast

Algorithm Progress

Target Node

Phase

Initialize

Pointer Positions

Slow

dummy

Fast

1

Target

N Parameter

Remove the 2nd node from the end of the list.

Algorithm Insight

The dummy node pattern: create a node (0) pointing to head. Fast starts at head, slow at dummy. Fast moves n steps ahead, then both move until fast is null. Slow ends up before target. Works for all cases including head removal. O(n) time, O(1) space.

Press "Start" to create dummy node and initialize pointers, n = 2.

Pointer State

slowdummy
fast1
targetNone

Why This Step Matters

Dummy node created pointing to head. Fast starts at head, slow at dummy. Fast will move 2 steps ahead.

Current Action

Initialize: dummy created, fast = head (1), slow = dummy, n = 2

Step Explanation

Setup

Initialize Pointers

Create dummy node (0) pointing to head. Fast starts at head, slow at dummy.

  • > Phase: Setup
  • > dummy = ListNode(0, head)
  • > n = 2: remove 2nd node from end
  • > Dummy node ensures we can remove head without special case
  • > Dummy node ensures we can remove head without special case.
Unvisited
Current (Slow)
Done
Fast Pointer