Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example:
Input: head = [1, 2, 3, 4, 5], n = 2
Output: [1, 2, 3, 5]
Constraints:
sz
.1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
n
is always valid, i.e., 1 <= n <= sz
?
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
# Create a dummy node to handle edge cases more easily
dummy = ListNode(0, head)
first = dummy
second = dummy
# Move first pointer so that there is a gap of n nodes between first and second
for _ in range(n + 1):
first = first.next
# Move both pointers until first reaches the end
while first is not None:
first = first.next
second = second.next
# Remove the nth node from end
second.next = second.next.next
# Return the new head
return dummy.next
first
and second
).first
pointer by n + 1
steps from the dummy node. This ensures that the gap between first
and second
is n
nodes.first
pointer reaches the end.second
pointer is at the node right before the node to be removed.next
pointer of the second
node to skip the node to be removed.dummy.next
which points to the updated head of the list.O(L)
where L
is the number of nodes in the linked list. We traverse the list once.O(1)
because we only use a fixed amount of extra space (pointers).This approach ensures that we efficiently remove the nth node from the end of the list with a single pass through the list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?