Delete Node in a Linked List — LeetCode 237 Python Solution

MediumLinked List
Problem
#237
Reading time
3 min

The problem

There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node.

Example

Input
head = [4,5,1,9], node = 5
Output
[4,1,9]
Explanation
You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 237. Delete Node in a Linked List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 237. Delete Node in a Linked List?
LeetCode 237. Delete Node in a Linked List is rated Medium on LeetCode.
What is the time complexity of LeetCode 237. Delete Node in a Linked List?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 237. Delete Node in a Linked List?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 237. Delete Node in a Linked List cover?
LeetCode 237. Delete Node in a Linked List is tagged Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview