Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Method 1: Find length L, remove (L-n)th node from start
- T.C O(n) but 2 pass, S.C O(1)
- Method 2: Recursion (count from end while returning)
- T.C O(n), S.C O(n) due to recursion stack
- Method 3: Two pointers (FAST-SLOW) <-- used here
- Move fast pointer n steps ahead.
- If fast becomes None => removing head (n == size), return head.next
- Else move slow and fast together until fast reaches last node.
- Now slow.next is the node to delete.
- T.C O(n) one pass, S.C O(1)
- '''
- # 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: Optional[ListNode], n: int) -> Optional[ListNode]:
- fast=head
- while fast and n>0:
- fast=fast.next
- n-=1
- if not fast: #remove nth elmenet in a n size linked list
- return head.next
- slow=head
- while fast.next!=None:
- slow=slow.next
- fast=fast.next
- slow.next=slow.next.next
- return head
Advertisement
Add Comment
Please, Sign In to add comment