Middle of the Linked List

easy · slow/fast pointers

You are given the head of a singly linked list. Return the middle node of the list. If there are two middle nodes, return the second one. Do it in a single pass without first counting the nodes. The nodes are ListNode objects with val and next. Constraints 1 ≤ nodes ≤ 100; 1 ≤ val ≤ 100. Examples [1,2,3,4,5] → the sublist starting at 3, i.e. [3,4,5] [1,2,3,4,5,6] → [4,5,6]

Starter code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def middle_node(head: ListNode | None) -> ListNode | None:
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from BreakPy’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. AntyCharacter joke · No posting date

    I asked the hash for one shard. It gave me a lecture on consistency.

  2. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  3. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.