Remove Nth Node From End of List

Medium· two pointers· dummy head

Problem

Delete the node that is n positions from the end of a linked list and return the head. Try to do it in a single pass over the list.

Examples

Input: head = [10,20,30,40,50], n = 2
Output: [10,20,30,50]
The 2nd node from the end holds 40.
Input: head = [1], n = 1
Output: []

Constraints

  • • 1 <= list length <= 30
  • • 1 <= n <= list length

Hints & approach

Hint 1

Two passes work: count the length, then walk to the node before the target.

Hint 2

For one pass, keep two pointers exactly n nodes apart.

Hint 3

Start both at a dummy node so removing the head needs no special case.

Approachtry the hints first

Put a dummy node before head and start two pointers there. Advance the lead pointer n + 1 steps, then move both together until the lead falls off the end. The trailing pointer now sits just before the node to delete, so set trailing.next = trailing.next.next. Return dummy.next, which correctly handles deleting the original head.

Time O(n) · Space O(1)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.