#876

Middle of the Linked List

Easy
Linked ListTwo PointersTwo PointersLinked List
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)

Using the two-pointer technique, we can find the middle node in a single pass through the list. One pointer moves twice as fast as the other, allowing us to find the middle efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, slow and fast, both pointing to the head.
  2. 2Step 2: Move slow by one step and fast by two steps until fast reaches the end of the list.
  3. 3Step 3: When fast is null or fast.next is null, slow will be at the middle node.
  4. 4Step 4: Return the slow pointer.
solution.py13 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def middleNode(head):
8    slow = head
9    fast = head
10    while fast and fast.next:
11        slow = slow.next
12        fast = fast.next.next
13    return slow

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 fixed amount of space for the pointers.

  • 1Using two pointers can significantly reduce time complexity.
  • 2Understanding the structure of linked lists is crucial for solving related problems.

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