Data Structures

Delete Nth Node

Linked List

Given the head of a linked list head and an index i, delete the ith element, and return the new head of the linked list.

The index will always be in bounds.

Example:

First Few Test Cases:

Here's an example linked list:

To delete an element, you can make the pointers "skip over" it. For example, here's how you delete the 2nd element:

The LinkedList acts as if the 2nd node was deleted, because the 1st node points to the 3rd node. And Python will automatically delete the 2nd node when it realizes it's no longer used.

In general, you can delete the ith element by pointing the i-1th element to the i+1th element. Here's the code for this:

This code usually works, but it breaks when i=0. This is because the code is supposed to step to the previous node i-1, but there is no previous node in that case.

To fix this, you can handle this case separately from the other cases. You should return the head.next node, like this:

Here's the full code for this problem:

Time Complexity O(n)O(n). You step through every node in the Linked List.

Space Complexity O(1)O(1). You store a single variable called node.

Mark as Completed:
Submits:
delete
Imports:
ListNode
Test your code to get an output here!
delete(
)
Test your code to get an output here!