Start learning free

LESSON 430 OF 675 · LINKED LISTS

Remove Nth Node from End of List

Practice O(n)

You get the head of a linked list and a number n. Delete the nth node from the end. Return the head of the list.

Count from the end: the last node is the 1st.

 

Example 1:

before after 3rd from end 6 2 9 4 7 6 2 4 7

Input: head = [6,2,9,4,7], n = 3
Output: [6,2,4,7]
Explanation: The red node, 9, is the 3rd from the end.
7 is the 1st and 4 is the 2nd.
After 9 goes, 2 links straight to 4.

Example 2:

Input: head = [8,5], n = 2
Output: [5]
Explanation: The 2nd node from the end is the head.
So the new head is the node with 5.

Example 3:

Input: head = [3], n = 1
Output: []
Explanation: Deleting the only node leaves an empty list.
Return null.

 

Constraints:

  • 1 to 30 nodes.
  • Each value is between 0 and 100.
  • n is from 1 to the length of the list.

 

Follow up: Can you do it in one walk along the list, without counting its length first?

STEP 1 OF 11
    Ctrl + Enter to check