Problem
Given thehead of a linked list, remove the n<sup>th</sup> node from the end of the list and return its head.
Examples
Constraints
- The number of nodes in the list is
sz. 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 19 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 19 # by problem number
lcpy gen -s remove_nth_node_from_end_of_list # by problem name
head of a linked list, remove the n<sup>th</sup> node from the end of the list and return its head.
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Input: head = [1], n = 1
Output: []
Input: head = [1,2], n = 1
Output: [1]
sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= szfrom leetcode_py import ListNode
class Solution:
# Time: O(L) where L is the length of the list
# Space: O(1)
def remove_nth_from_end(self, head: ListNode[int] | None, n: int) -> ListNode[int] | None:
dummy = ListNode(0)
dummy.next = head
fast: ListNode[int] | None = dummy
slow: ListNode[int] | None = dummy
# Move fast pointer n+1 steps ahead
for _ in range(n + 1):
assert fast
fast = fast.next
# Move both pointers until fast reaches end
while fast:
fast = fast.next
assert slow
slow = slow.next
# Remove the nth node
assert slow and slow.next
slow.next = slow.next.next
return dummy.next
| Time | Space |
|---|---|
| O(L) where L is the length of the list | O(1) |