#19

Remove Nth Node From End of List

Medium
Linked ListTwo PointersHash MapArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Two Pointers)
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using two pointers allows us to find the nth node from the end in a single pass. By advancing one pointer n steps ahead, we can then move both pointers until the first pointer reaches the end, at which point the second pointer will be at the node just before the one we want to remove.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, both starting at the head.
  2. 2Step 2: Move the first pointer n steps ahead.
  3. 3Step 3: Move both pointers until the first pointer reaches the end of the list.
  4. 4Step 4: The second pointer will now be at the node just before the one to be removed. Adjust the pointers to remove the target node.
solution.py26 lines
1# Full working Python code with comments
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7class Solution:
8    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
9        dummy = ListNode(0)
10        dummy.next = head
11        first = dummy
12        second = dummy
13
14        # Step 2: Move first pointer n steps ahead
15        for _ in range(n + 1):
16            first = first.next
17
18        # Step 3: Move both pointers until first reaches the end
19        while first:
20            first = first.next
21            second = second.next
22
23        # Step 4: Remove the nth node
24        second.next = second.next.next
25
26        return dummy.next

Complexity note: The time complexity is O(n) because we traverse the list only once. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Using two pointers allows for an efficient solution that only requires a single pass through the linked list.
  • 2The dummy node pattern helps handle edge cases like removing the head of the list without additional checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.