Remove Nth Node From End of List

Medium
Fast & Slow Pointers

Given the head of a linked list, remove the nth node from the end of the list and return its head.

This problem uses a variation of the two-pointer technique where the gap between pointers helps us locate a specific position from the end. By maintaining a fixed gap of n nodes between two pointers and advancing both until the fast pointer reaches the end, the slow pointer will be perfectly positioned.

Example 1

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Explanation: We remove the 2nd node from the end (value 4).

Example 2

Input: head = [1], n = 1
Output: []
Explanation: The only node is removed, resulting in an empty list.

Example 3

Input: head = [1,2], n = 1
Output: [1]
Explanation: We remove the last node (value 2).

Constraints

  • The number of nodes in the list is sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz
Show Hints (4)
Hint 1: If you knew the length of the list, which node would you remove (from the beginning)?
Hint 2: Can you determine the position without first counting all nodes?
Hint 3: What if one pointer gets a head start of n nodes?
Hint 4: Consider using a dummy node before head to handle the case of removing the first node elegantly.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?