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]
Example 2
Input: head = [1], n = 1
Output: []
Example 3
Input: head = [1,2], n = 1
Output: [1]
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
pSlow = pFast = dummy = ListNode(-1)
dummy.next = head
for _ in range(n):
pFast = pFast.next
while pFast.next:
pFast = pFast.next
pSlow = pSlow.next
targetNode = pSlow.next
pSlow.next = pSlow.next.next
del targetNode
return dummy.next
Time Complexity: O(N)
Space Complexity: O(1)
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
ptrFast = head
for _ in range(n):
ptrFast = ptrFast.next
# n == size of list
if not ptrFast:
return head.next
ptrSlow = head
while ptrFast.next:
ptrFast = ptrFast.next
ptrSlow = ptrSlow.next
targetNode = ptrSlow.next
ptrSlow.next = ptrSlow.next.next
del targetNode
return head
Time Complexity: O(N)
Space Complexity: O(1)
https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8802/3-short-Python-solutions
TODO
Time Complexity: O()
Space Complexity: O()