Drop the nth node from the end
MediumStuck?
Show a hintHide the hint
Put a dummy before the head, move one reference n steps ahead, then move both until it reaches the end. The trailing one now sits just before the node to drop.
The ideas behind this problem
Next in this lesson
Turn the list aroundRemove the nth node counting from the end of the list, and return the head.
Worked example#
For 1 -> 2 -> 3 -> 4 -> 5 with n = 2, the second from the end is 4, so the answer is 1 2 3 5.
Counting from the end without knowing the length#
Start two references at the front and move the first one n steps ahead. Now hold that gap and move both together. When the leading one reaches the end, the trailing one is exactly n from the end.
With n = 2:
| lead | trail | note |
|---|---|---|
| 3 | 1 | the gap is set: lead is two ahead |
| 4 | 2 | |
| 5 | 3 | trail is now just before the node to remove |
| off the end | stop |
The trailing reference is at 3, and 3's next is the node to drop, so point 3 at 5.
To remove a node you need the one before it, which is why the trailing reference is deliberately parked one short.
The case that breaks a first attempt#
What if the node to remove is the head itself, as in 1 -> 2 with n = 2? There is no node before it, so there is nothing to rewire.
A dummy node in front of the head removes the special case entirely: the head now has something before it like every other node, and the answer is dummy.next. Without it you need a separate branch, and forgetting that branch is the usual bug.
The cost#
Time O(n), one pass. Memory O(1).
Constraints#
1 <= number of nodes <= 301 <= n <= number of nodes0 <= value <= 100
Input
head is a count then that many values. Then n is one integer.
Output
The list after the removal, values separated by spaces.
Examples
Input
5 1 2 3 4 5 2
Output
1 2 3 5
The second from the end is 4.
Input
1 1 1
Output
Removing the only node leaves an empty list.
Input
2 1 2 2
Output
2
The node to remove is the head, which is why a dummy in front helps.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.