Problem
Solution
Need to find a way to both reach the end of the list with one pointer (so that we can find the n'th node from the end) and also the n'th node from the end simultaneously with a second pointer.
Fast pointer will have a head start by n nodes. This will cause slow pointer to reach the n'th node from the end at the same time that fast pointer reaches the end.
Actually, slow pointer need access to the node before the target node, so use fast.next == null as the exit condition instead of fast==null to stop one node earlier.
To handle the edge case where n is the same as the length of the list (target node is the head), just return head.next.
# 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 = slow = head
for _ in range(n):
fast = fast.next
# if n is equal to the len of list, fast should have gone beyond the end of list
# so remove the head
if not fast:
return head.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return head
JS, Python, Java, C++ | Easy Two-Pointer Solution w/ Explanation - LeetCode Discuss
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Time Complexity
O(N)
Space Complexity
O(1)
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[Coderust] Merge Two Sorted Linked Lists (0) | 2022.05.22 |
---|---|
[Coderust] Swapping Nodes in a Linked List (0) | 2022.05.21 |
[Coderust] Intersection of Two Linked Lists (0) | 2022.05.17 |
[Coderust] Remove Duplicates from a Linked List (0) | 2022.03.10 |
[Coderust] Implementation of Linked List (0) | 2022.03.08 |