Remove Nth Node From End of List
LeetCode 19 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Gap of n between two pointers.
ನಾನು Remove Nth Node From End of List (LeetCode 19) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Fast & Slow Pointers ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Give a fast pointer an n-node head start. Then move both pointers together; when fast reaches the last node, slow sits right before the node to delete.
Approach
- 1
Counting version: find the length, then walk to length − n.
- 2
Two-pointer version: advance fast n steps.
- 3
If fast is None, the head is the one to remove.
- 4
Move both until fast.next is None, then unlink slow.next.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ
Length first.
Fixed gap.
Count then walkPythonO(n) time · two passes
# 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]:
length=0
node = head
while node:
length+=1
node = node.next
#remove head case
if length ==n:
return head.next
#need to remove 5-2+1
from_left_count = length-n
count=1
node = head
while node:
if count == from_left_count:
if node.next:
node.next = node.next.next
break
count+=1
node = node.next
return headTwo pointers, one passPythonO(n) time · O(1) space
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
fast = head
k = n
while k!=0:
fast = fast.next
k-=1
#head case
if fast==None:
return head.next
#fast is now 2 positions ahead, fast will reach to the end faster
slow = head
while fast.next:
slow = slow.next
fast = fast.next
#when fast reached end, slow just reached the prev node of the node to be deleted
slow.next=slow.next.next
return headRemove Nth Node From End of List — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Remove Nth Node From End of List ಹಿಂದಿನ intuition ಏನು?
Give a fast pointer an n-node head start. Then move both pointers together; when fast reaches the last node, slow sits right before the node to delete.
Remove Nth Node From End of List (LeetCode 19) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Counting version: find the length, then walk to length − n. 2. Two-pointer version: advance fast n steps. 3. If fast is None, the head is the one to remove. 4. Move both until fast.next is None, then unlink slow.next.
Remove Nth Node From End of List ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Two pointers, one pass.)
Remove Nth Node From End of List ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Removing the head is a special case without a dummy node.
Remove Nth Node From End of List ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?
Count then walk (O(n) time · two passes): Length first. Two pointers, one pass (O(n) time · O(1) space): Fixed gap.