Remove Nth Node From End of List
medium · two pointers with gap / dummy node
You are given the head of a linked list and an integer n. Remove the nth node from the end of the list and return the head of the modified list. The node to remove always exists (1 ≤ n ≤ length of the list). Do it in one pass. The nodes are ListNode objects with val and next.
Constraints
1 ≤ nodes ≤ 30; 1 ≤ n ≤ number of nodes; 0 ≤ val ≤ 100.
Examples
[1,2,3,4,5], n=2 → [1,2,3,5]
[1], n=1 → []
[1,2], n=1 → [1]
Starter code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_nth_from_end(head: ListNode | None, n: int) -> ListNode | None:
pass
Loading editor…
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python interpreter