Remove Nth Node From End of List Medium 0 attempts
LeetCode ↗

Remove Nth Node From End of List

Medium Linked List LeetCode

You're given the head of a linked list and an integer n. Delete the node sitting n positions from the end of the list, then return the head of what remains.

Input Format
Implement removeNthFromEnd(head, n). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement. Returned list heads are displayed as value arrays; a null head is [].

Sample Input and Output

Example 1 ยท Run Sample

Input
head = [1,2,3,4,5]
n = 2
Output
[1,2,3,5]

Example 2

Input
head = [1]
n = 1
Output
[]
Constraints
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz
Test Cases (2)
Case 1
Args: [[1,2,3,4,5],2] Expected: [1,2,3,5]
Case 2
Args: [[1],1] Expected: []
Topics

Two Pointer (Gap of n)

javascript
function removeNthFromEnd(head, n) {
  const dummy = {next: head};
  let fast = dummy, slow = dummy;
  for (let i = 0; i <= n; i++) fast = fast.next;
  while (fast) { fast = fast.next; slow = slow.next; }
  slow.next = slow.next.next;
  return dummy.next;
}

Time: O(L) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript