EasyNo. 0876

Middle of the Linked List — LeetCode 876 Python Solution

Topics
Linked List, Two Pointers
On a study list
Grind 75
Reading time
2 min

The problem

Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.

Example

Input
head = [1,2,3,4,5]
Output
[3,4,5]
Explanation
The middle node of the list is node 3.

Python solution

PythonSolution
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        return slow

Complexity

Time
O(n) (after optional sort O(n log n))
Space · auxiliary
O(1)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 876. Middle of the Linked List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0019Remove Nth Node From End of ListMedium
0061Rotate ListMedium
0082Remove Duplicates from Sorted List IIMedium
0086Partition ListMedium
0148Sort ListMedium
1721Swapping Nodes in a Linked ListMedium

Frequently asked questions

How hard is LeetCode 876. Middle of the Linked List?

LeetCode 876. Middle of the Linked List is rated Easy on LeetCode.

What is the time complexity of LeetCode 876. Middle of the Linked List?

The Python solution on this page runs in O(n) (after optional sort O(n log n)).

What is the space complexity of LeetCode 876. Middle of the Linked List?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 876. Middle of the Linked List cover?

LeetCode 876. Middle of the Linked List is tagged Linked List and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.