19. Remove Nth Node From End of List ๐๏ธ
Last updated
Last updated
Difficulty: Medium
- Tags: Linked List
, Two Pointers
Given the head of a linked list, remove the n
th node from the end of the list and return its head.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
The number of nodes in the list is sz
.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
We can solve this problem in one pass by using the two-pointer technique. The first pointer moves n
steps ahead, and then both pointers move together until the first pointer reaches the end. This ensures the second pointer is just before the node to be removed.
Dummy Node:
A dummy node is used to handle edge cases where the head needs to be removed.
Two-Pointer Technique:
The first pointer moves n+1
steps ahead, so when it reaches the end, the second pointer is just before the node to be removed.
Node Removal:
Adjust the next
pointer of the second pointer to skip the node to be removed.
O(sz): The list is traversed once to find and remove the node.
O(1): The solution uses constant space.
Could you do this in one pass?
The above solution achieves the removal in a single pass using the two-pointer approach, maintaining optimal time complexity.
You can find the full solution here.