Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Remove Nth Node From End

Linked Listsmedium

A linked list is given as an array of values in order (e.g. `[1,2,3,4,5]`). Implement `removeNthFromEnd(arr, n)` that removes the **n-th node from the end** of the list and returns the resulting array. `n` is always valid (1 ≤ n ≤ arr.length). Example: `removeNthFromEnd([1,2,3,4,5], 2)` → `[1,2,3,5]` (the 2nd from end, which is `4`, is removed).

Sample tests

Input: removeNthFromEnd([1,2,3,4,5], 2)
Output: [1,2,3,5]
Input: removeNthFromEnd([1,2,3,4,5], 1)
Output: [1,2,3,4]
Input: removeNthFromEnd([1,2,3,4,5], 5)
Output: [2,3,4,5]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Off-by-one when translating n-from-the-end into a forward index.

Learning resources

  • MDN: Array.prototype.splice
Approach & explanation (try first)

With an array representation the n-th from the end is at index length minus n, removed in O(n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.