imashutosh51

Remove Nth Node From End of List

Aug 10th, 2022 (edited)
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. '''
  2. Method 1: Find length L, remove (L-n)th node from start
  3.         T.C O(n) but 2 pass, S.C O(1)
  4.  
  5. Method 2: Recursion (count from end while returning)
  6.         T.C O(n), S.C O(n) due to recursion stack
  7.  
  8. Method 3: Two pointers (FAST-SLOW)  <-- used here
  9.    Move fast pointer n steps ahead.
  10.    If fast becomes None => removing head (n == size), return head.next
  11.    Else move slow and fast together until fast reaches last node.
  12.    Now slow.next is the node to delete.
  13.    T.C O(n) one pass, S.C O(1)
  14. '''
  15. # Definition for singly-linked list.
  16. # class ListNode:
  17. #     def __init__(self, val=0, next=None):
  18. #         self.val = val
  19. #         self.next = next
  20. class Solution:
  21.     def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
  22.         fast=head
  23.         while fast and n>0:
  24.             fast=fast.next
  25.             n-=1
  26.         if not fast: #remove nth elmenet in a n size linked list
  27.             return head.next
  28.         slow=head
  29.         while fast.next!=None:
  30.             slow=slow.next
  31.             fast=fast.next
  32.         slow.next=slow.next.next
  33.         return head
  34.        
Advertisement
Add Comment
Please, Sign In to add comment