Remove the nth node from the end
Medium TimeO(n) SpaceO(1)
Given the head of a linked list and a number n, remove the nth node counting from the end and return the head — taking the 2nd-from-last out of [1, 2, 3, 4, 5] leaves [1, 2, 3, 5]. n counts from 1, so n = 1 is the last node; n is never larger than the list, and removing the head is allowed and changes what comes back.
Examples
Example 1
- Input
- node = removeNthFromEnd(buildList([1, 2, 3, 4, 5]), 2)
- Output
- The 2nd from the end is the
[1,2,3,5]4, and taking it out leaves the other four.
Example 2
- Input
- node = removeNthFromEnd(buildList([1, 2, 3, 4, 5]), 5)
- Output
- Five from the end of five nodes is the head itself, so the list now starts at
[2,3,4,5]2.
The Code
function buildList(values) {
let head = null;
for (let i = values.length - 1; i >= 0; i--) {
head = { val: values[i], next: head };
}
return head;
}
function toArray(node) {
const out = [];
while (node) {
out.push(node.val);
node = node.next;
}
return out;
}
function removeNthFromEnd(head, n) {
const dummy = { val: 0, next: head };
let lead = dummy;
let trail = dummy;
for (let i = 0; i < n; i++) {
lead = lead.next;
}
while (lead.next) {
lead = lead.next;
trail = trail.next;
}
trail.next = trail.next.next;
return dummy.next;
}
toArray(removeNthFromEnd(buildList([1, 2, 3, 4, 5]), 2));More like this
All linked lists examples (9) →- Reverse a list Three pointers, one pass — flip every link as you walk.
- Detect a cycle A slow and a fast pointer must meet if the list loops.
- Middle node When the fast pointer finishes, the slow one is halfway.
- Merge two lists A dummy head removes every special case for the first node.
- Palindrome list A list can’t be read backwards — so copy it out, then close in.
- Merge k lists Merge lists in pairs, halving how many remain each round.