#2095

Delete the Middle Node of a Linked List

Medium
Linked ListTwo PointersTwo PointersLinked List Manipulation
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution uses two pointers to find the middle node while keeping track of the previous node. This approach is efficient and only requires a single pass through the list.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers, slow and fast. Slow moves one step at a time, while fast moves two steps.
  2. 2Step 2: As you traverse, keep track of the previous node to the slow pointer.
  3. 3Step 3: When the fast pointer reaches the end, the slow pointer will be at the middle node. Adjust the previous node's next pointer to skip the middle node.
solution.py17 lines
1class ListNode:
2    def __init__(self, val=0, next=None):
3        self.val = val
4        self.next = next
5
6def deleteMiddle(head):
7    if not head or not head.next:
8        return None
9    slow = head
10    fast = head
11    prev = None
12    while fast and fast.next:
13        prev = slow
14        slow = slow.next
15        fast = fast.next.next
16    prev.next = slow.next
17    return head

Complexity note: The time complexity is O(n) because we traverse the list only once. The space complexity is O(1) since we only use a few pointers.

  • 1Using two pointers can significantly reduce the number of traversals needed.
  • 2Maintaining a reference to the previous node is crucial for modifying the list.

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