
Problem Statement
Given a linked list, remove the last nth node from the end of the list and return the head of the modified list.
Example 1:
- Input: list = 1 -> 2 -> 3 -> 4 -> 5, n = 2
- Expected Output: 1 -> 2 -> 3 -> 5
- Justification: The 2nd node from the end is "4", so after removing it, the list becomes [1,2,3,5].
Example 2:
- Input: list = 10 -> 20 -> 30 -> 40, n = 4
- Expected Output: 20 -> 30 -> 40
- Justification: The 4th node from the end is "10", so after removing it, the list becomes [20,30,40].
Example 3:
- Input: list = 7 -> 14 -> 21 -> 28 -> 35, n = 3
- Expected Output: 7 -> 14 -> 28 -> 35
- Justification: The 3rd node from the end is "21", so after removing it, the list becomes [7,14,28,35].
Constraints:
- The number of nodes in the list is
sz. 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Solution
-
Two-Pass Approach:
- Begin by calculating the length of the linked list. This can be done by traversing the list from the head to the end.
- Once the length is determined, calculate which node to remove by subtracting
nfrom the length. - Traverse the list again and remove the node at the calculated position.
-
One-Pass Approach using Two Pointers:
- Use two pointers,
firstandsecond, and place them at the start of the list. - Move the
firstpointernnodes ahead in the list. - Now, move both
firstandsecondpointers one step at a time until thefirstpointer reaches the end of the list. Thesecondpointer will now bennodes from the end. - Remove the node next to the
secondpointer.
- Use two pointers,
-
Advantage of One-Pass Approach:
- The one-pass approach is more efficient as it traverses the list only once, whereas the two-pass approach requires two traversals.
-
Edge Cases:
- If
nis equal to the length of the list, remove the head of the list.
- If
Algorithm Walkthrough
Let's trace the first example, 1 -> 2 -> 3 -> 4 -> 5 with n = 2. Move through the steps one at a time:
Step 1. Counting the length first and then walking again would work, but it reads the list twice. Instead, open a gap between two pointers that is exactly 2 nodes wide, then slide both along together. When the leading pointer runs off the end, the trailing one is sitting exactly 2 nodes from the end. The dashed box in front is a dummy node: with it there, removing the very first node needs no special case, because the trailing pointer always has something to point from.
1 of 6
Code
Complexity Analysis
- Time Complexity: O(L) - We traverse the list with two pointers. Here, L is the number of nodes in the list.
- Space Complexity: O(1) - We only used constant extra space.