Remove Nth Node From End of List

Problem Id: 19 Difficulty: Medium Tag: Linked List Tag: Two Pointers


Intuition

Use 2 pointers.

  1. The first pointer goes n steps.
  2. Two pointer go together until the first pointer reached the end.
  3. Remove the second pointer.

Solution


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        first = head
        second = head
        for _ in range(n):
            first = first.next

        if not first.next:
            return head.next

        while first.next:
            first = first.next
            second = second.next
        second.next = second.next.next
        return head