Typorithm · medium

Remove Nth From End

remove-nth-from-endlinked-liststwo-pointer-gapdummy-nodeone-pass
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Remove Nth From End

0%

Linked Lists

Open an n-node gap between two pointers, then move both until slow sits before the target.

Removing the nth-from-end node naively needs the length first, a two-pass approach.

Advancing fast n steps ahead creates a fixed gap; when fast reaches the end, slow is just before the target.

A dummy node makes removing the head a non-special case.

01

Gap of n between fast and slow.

02

Stop when fast is at the last node.

03

Dummy handles head removal.

function removeNthFromEnd(head, n) {
  const dummy = { val: 0, next: head };
  let fast = dummy;
  let slow = dummy;

  for (let i = 0; i < n; i += 1) {
    fast = fast.next;
  }

  while (fast.next !== null) {
    fast = fast.next;
    slow = slow.next;
  }

  slow.next = slow.next.next;
  return dummy.next;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Dummy before head

A dummy handles removing the head uniformly.

const dummy = { val: 0, next: head }

2. Open the gap

Advance fast n nodes ahead of slow.

for (let i = 0; i < n; i += 1)

3. Walk together

Move both until fast reaches the last node.

while (fast.next !== null)

4. Unlink target

slow sits just before the node to remove.

slow.next = slow.next.next

5. Return head

dummy.next is the possibly-changed head.

return dummy.next

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Remove Nth From End: Lesson & Practice · Typorithm | ApplyDjinn