Problem Statement: Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Constraints:
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Asked in: Facebook Amazon ,Apple Netflix Google
Leetcode Difficulty: Medium
Code:
def removeNthFromEnd(self, head, n):
"""
head: ListNode
n: int
return: ListNode
"""
fastptr=head
slowptr=head
prev=None
count=1
while count!=n:
fastptr=fastptr.next
count+=1
while fastptr.next:
fastptr=fastptr.next
prev=slowptr
slowptr=slowptr.next
if prev:
prev.next=slowptr.next
else:
head = slowptr.next
return head
Thought Process / Explanation:
You can always find the length first and then iterate (L-n) positions from start. But that would require you to do 2 passes on the entire list. So for a single pass, clearly, we need to maintain 2 ptrs (Fast and Slow pointers are very useful in solving LL questions) One starts at the nth position from start and another from Zeroth. By the time ahead one reaches NULL, the previous one will reach the nth position from the end.
Thank You!
No comments:
Post a Comment
Please share your valuable feedback. It will help me and community grow.