Facebook PixelRemove Nth Node From End of List — Coding Practice
Remove Nth Node From End of ListMedium

Remove Nth Node From End of List

Medium 16.8k47% acceptance
Linked ListTwo Pointers

Given the head of a singly linked list and an integer n, remove the n-th node counting from the end of the list, then return the head of the resulting list.

The list is given to you as a ListNode ({ val, next }); an empty list is null. n is always valid (1 ≤ n ≤ length). If removing the node leaves the list empty, return the empty list ([]).

Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
The 2nd node from the end holds the value 4, so it is removed.
Example 2
Input: head = [1], n = 1
Output: []
Removing the only node leaves an empty list.
Example 3
Input: head = [1,2], n = 1
Output: [1]
Constraints
  • The number of nodes is in the range [1, 30].
  • 0 ≤ Node.val ≤ 100
  • 1 ≤ n ≤ number of nodes
Asked atAmazonMetaMicrosoftGoogle
JavaScript
Loading editor…
Case 1
[1,2,3,4,5], 2
expected: [1,2,3,5]
Case 2
[1], 1
expected: []
Case 3
[1,2], 1
expected: [1]
Case 4
[1,2], 2
expected: [2]
Case 5
[1,2,3], 3
expected: [2,3]
Case 6
[7,8,9,10], 4
expected: [8,9,10]