SDE & MLE Prep

876. Middle of the Linked List

Problem

Return the middle node of a linked list; when there are two middle nodes, return the second.

Example: 1→2→3→4→5 → node 3; 1→2→3→4→5→6 → node 4

Fast moves two steps, slow one; when fast runs out, slow is at the middle (the second middle for even lengths).

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

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