#237

Delete Node in a Linked List

Medium
Linked ListPointer ManipulationLinked List
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Instead of traversing the list to find the previous node, we can directly copy the value from the next node into the current node and then skip the next node. This is efficient and works in one pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Copy the value from the next node into the current node.
  2. 2Step 2: Change the next pointer of the current node to skip the next node.
  3. 3Step 3: The next node is effectively deleted.
solution.py9 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def deleteNode(node):
8    node.val = node.next.val
9    node.next = node.next.next

Complexity note: This complexity is constant because we only perform a fixed number of operations regardless of the size of the linked list.

  • 1The node to be deleted is guaranteed to not be the last node.
  • 2We can manipulate the pointers directly to achieve deletion without needing the head.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.