Remove Nth Node From End
Medium linked-list · two-pointers
Description
Constraints
1 <= n <= length
Examples
Input: list = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Hints (1)
- Advance a lead pointer n steps, then move both until the lead reaches the end.
Solutions
One pass with two pointers. · Time O(n) · Space O(1)
func removeNthFromEnd(list []int, n int) []int {
idx := len(list) - n
out := append([]int{}, list[:idx]...)
out = append(out, list[idx+1:]...)
return out
}
One pass with two pointers. · Time O(n) · Space O(1)
function removeNthFromEnd(list, n) {
const out = [...list];
out.splice(out.length - n, 1);
return out;
}
One pass with two pointers. · Time O(n) · Space O(1)
function removeNthFromEnd($list, $n) {
$len = count($list);
$idx = $len - $n;
array_splice($list, $idx, 1);
return $list;
}
One pass with two pointers. · Time O(n) · Space O(1)
def removeNthFromEnd(list, n):
out = list[:]
del out[len(out) - n]
return out
One pass with two pointers. · Time O(n) · Space O(1)
function removeNthFromEnd(list: number[], n: number): number[] {
const out = [...list];
out.splice(out.length - n, 1);
return out;
}
Create a free account to submit solutions, track progress and save problems.
Create account