Remove Nth Node From End of List in Python

Removing the Nth node from the end of a linked list is a common programming problem. Given a linked list and a number n, we need to remove the node that is n positions from the end and return the modified list head.

For example, if we have a list [1, 2, 3, 4, 5, 6] and n = 3, we remove the 3rd node from the end (which is 4), resulting in [1, 2, 3, 5, 6].

Algorithm Steps

We use a two-pointer approach to solve this efficiently ?

  • If there is only one node in the list, return None
  • Initialize two pointers: front and back, both pointing to head
  • Move the front pointer n+1 steps ahead
  • If front becomes None during this process, we need to remove the head node
  • Move both pointers until front reaches the end
  • Remove the node after back pointer
  • Return the head

Implementation

class ListNode:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    current = head
    for element in elements[1:]:
        current.next = ListNode(element)
        current = current.next
    return head

def print_list(head):
    result = []
    current = head
    while current:
        result.append(str(current.val))
        current = current.next
    print("[" + ", ".join(result) + "]")

class Solution:
    def removeNthFromEnd(self, head, n):
        # Handle single node case
        if not head.next:
            return None
        
        front = head
        back = head
        counter = 0
        flag = False
        
        # Move front pointer n+1 steps ahead
        while counter <= n:
            if not front:
                flag = True
                break
            front = front.next
            counter += 1
        
        # Move both pointers until front reaches end
        while front:
            front = front.next
            back = back.next
        
        # Remove the target node
        if not flag:
            temp = back.next
            back.next = temp.next
            temp.next = None
        else:
            # Remove head node
            head = head.next
        
        return head

# Example usage
elements = [1, 2, 3, 4, 5, 6]
head = make_list(elements)
print("Original list:")
print_list(head)

solution = Solution()
modified_head = solution.removeNthFromEnd(head, 3)
print("After removing 3rd node from end:")
print_list(modified_head)
Original list:
[1, 2, 3, 4, 5, 6]
After removing 3rd node from end:
[1, 2, 3, 5, 6]

How It Works

The algorithm uses the two-pointer technique:

  • Step 1: Move the front pointer n+1 positions ahead of the back pointer
  • Step 2: Move both pointers simultaneously until front reaches the end
  • Step 3: The back pointer will now be at the node just before the target node
  • Step 4: Remove the target node by adjusting the next pointer

Edge Cases

The solution handles two important edge cases ?

  • Single node list: If there's only one node and n=1, return None
  • Remove head node: If n equals the list length, remove the head node

Time and Space Complexity

  • Time Complexity: O(L) where L is the length of the linked list
  • Space Complexity: O(1) as we only use a constant amount of extra space

Conclusion

The two-pointer approach efficiently removes the Nth node from the end in a single pass. This technique maintains O(1) space complexity while handling all edge cases including removing the head node.

Updated on: 2026-03-25T07:44:24+05:30

777 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements