Skip to main content

3 - Remove nth Node From End of List

Problem Statement

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

Example 1:

Input: n = 3
23 -> 28 -> 10 -> 5 -> 67 -> 39 -> 70 -> Null

Output:
23 -> 28 -> 10 -> 5 -> 39 -> 70 -> Null

Constraints:

  • The number of nodes in the list is k.
  • 1 ≤ k ≤ 10^4
  • −10^3 ≤ Node.value ≤10^3
  • 1 ≤ n ≤ Number of nodes in the list

Linked List Starter Code

Written by @kondekarshubham123
# Template for linked list node class

class LinkedListNode:
# __init__ will be used to make a LinkedListNode type object.
def __init__(self, data, next=None):
self.data = data
self.next = next

Approch 1: Using Two Pointer approch

Written by @kondekarshubham123
from linked_list import LinkedList
from linked_list_node import LinkedListNode

def remove_nth_last_node(head, n):
dummy = LinkedList()
dummy.next = head
first = dummy
second = dummy

for _ in range(n+1):
first = first.next

while first is not None:
first = first.next
second = second.next

second.next = second.next.next

return dummy.next