Week 3 ยท Linked List
Remove Nth Node From End of List
Remove the nth node from the end in one pass. The runner uses values and n.
Medium Linked List Week 3 Practice runner
Frame the problem
- n is counted from the end.
- Deleting the head is possible.
- The one-pass version uses a fast/slow gap of n.
1. Reveal example inputs and outputs
Example 1
Input:
remove_nth_from_end_values([
1,
2,
3,
4,
5
], 2) Output:
[
1,
2,
3,
5
] Example 2
Input:
remove_nth_from_end_values([
1,
2
], 2) Output:
[
2
] 2. Brute force first
How would length counting solve it in two passes? How does a fast pointer make it one pass?
3. Reveal the insight ladder
- Create a dummy node.
- Move fast n steps ahead.
- Move fast and slow together.
- slow.next is the node to delete.
4. Dry run before code
- [1,2,3,4,5], n = 2.
- Slow stops before 4.
- Bypass 4 to return [1,2,3,5].
5. Reveal final Python solution
def remove_nth_from_end_values(values, n):
index = len(values) - n
return values[:index] + values[index + 1:] Complexity: Pointer one-pass version: time O(n), space O(1).
Interview narration
- The dummy node gives the head a predecessor.
- The fast pointer creates the offset from the end.
- When fast reaches the end, slow is before the target.
Common traps
- Off-by-one positioning.
- Failing to delete the head.
- Not handling a single-node list.
Follow-up drills
1. Why use a dummy node?
It makes deleting the original head the same as deleting any other node.
2. Is two-pass acceptable?
Often yes if not constrained, but the one-pass fast/slow version is the stronger interview answer.
Interactive runner
Write the required Python function. Your code runs locally in this browser. Hints reveal one failing case at a time.