Skip to content

Remove Nth Node From End of List

MediumLeetCode #19Time O(n)Space O(1)

You get the head of a linked list and a number n. Remove the n-th node counting from the end (n = 1 is the last node) and return the head.

[1, 2, 3, 4, 5], n = 2 -> [1, 2, 3, 5] (removes 4)

The obvious method takes two passes: count the length L, then walk to node L - n. You can do it in one pass by making the list measure itself.

Use two pointers with a fixed gap of n nodes. Move fast ahead n steps first, then move both together. When fast reaches the last node, slow is exactly one node before the one to delete, so slow.next = slow.next.next removes it. Start both at a dummy head in front of the list. Then slow can stop before the real head, and removing the first node needs no special case.

Show solutionHide solution
def remove_nth_from_end(head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head) # so removing the head is not a special case
fast = slow = dummy
for _ in range(n):
fast = fast.next # open a gap of n nodes
while fast.next:
fast = fast.next
slow = slow.next # slow stops just before the target
slow.next = slow.next.next
return dummy.next
  • Time: O(n) — fast walks the list once; slow follows behind.
  • Space: O(1) — two pointers and a dummy node.
  • Removing the head (n equals the length). Without a dummy node, slow has nothing to stand on. With it, dummy.next becomes the new head.
  • Stopping condition off by one. Loop while fast.next exists so that slow ends before the target, not on it. You need the previous node to relink.
  • Return dummy.next, never the original head, which may have just been removed.
  • Single node list with n = 1 should return an empty list (None).

Remove Duplicates from Sorted List (LeetCode 83)

Section titled “Remove Duplicates from Sorted List (LeetCode 83)”

Delete nodes so each value appears once. The trick: walk with one pointer; while the next node has the same value, skip it with cur.next = cur.next.next, otherwise advance.

Swap every two adjacent nodes by relinking, not by changing values. The trick: a dummy head and a prev pointer. For each pair, rewire prev -> second -> first -> rest, then move prev to first.

Rotate the list right by k places. The trick: find the length and tail, reduce k modulo the length, link the tail to the head to make a ring, then break it at the right spot: the new head is length - k steps from the old head, so cut just before it.