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:

Delete Nth Node - image
First Few Test Cases:
delete(ListNode.of([0, 1, 2]), 1)
# ListNode.of([0, 2])
delete(ListNode.of([5, 6, 7]), 1)
# ListNode.of([5, 7])
delete(ListNode.of([1, 2, 3]), 0)
# ListNode.of([2, 3])

Here's an example linked list:

Delete Nth Node - image

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

head.delete(2)
Delete Nth Node - image

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:

def delete(head, i):

    node = head
    for _ in range(i-1): # walk to index `i-1`
        node = node.next

    node.next = node.next.next # point node i-1 to node i+1
    
    return head

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:

if i == 0:
    return head.next
Delete Nth Node - image

Here's the full code for this problem:

def delete(head, i):

    # if deleting index 0, return head.next
    if i == 0:
        return head.next

    # otherwise, walk to node i-1 and point it to node i+1
    node = head
    for _ in range(i-1): 
        node = node.next

    node.next = node.next.next
    
    return head

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.

Note: there is a "dummy node" trick you can use to effectively get rid of the i == 0 case. See the next problem.

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