SDE & MLE Prep

2095. Delete the Middle Node of a Linked List

Problem

Delete the middle node of a linked list of n nodes, the one at 0-based index ⌊n / 2⌋, and return the head (a single node becomes an empty list).

Example: 1→3→4→7→1→2→6 → 1→3→4→1→2→6; 1→2→3→4 → 1→2→4

Fast/slow pointers, but start fast two steps ahead so slow stops just before the middle (index ⌊n/2⌋), then unlink slow.next. A single node list becomes empty.

Complexity: O(n) time, O(1) space.

class Solution:
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head.next:
            return None
        slow, fast = head, head.next.next
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        slow.next = slow.next.next
        return head