Bird
Raised Fist0
DSA Pythonprogramming

Find Middle Element of Linked List in DSA Python

Choose your learning style10 modes available
Mental Model
To find the middle, use two pointers moving at different speeds so when the fast one reaches the end, the slow one is in the middle.
Analogy: Imagine walking on a path with a friend: you walk one step at a time, your friend runs two steps at a time. When your friend finishes the path, you are halfway through.
Head -> 1 -> 2 -> 3 -> 4 -> 5 -> null
Slow ↑
Fast ↑
Dry Run Walkthrough
Input: list: 1 -> 2 -> 3 -> 4 -> 5 -> null
Goal: Find the middle element of the linked list
Step 1: Initialize slow and fast pointers at head (node 1)
1 -> 2 -> 3 -> 4 -> 5 -> null
Slow ↑1
Fast ↑1
Why: Both pointers start at the beginning to begin traversal
Step 2: Move slow by 1 step to node 2, fast by 2 steps to node 3
1 -> [Slow->2] -> [Fast->3] -> 4 -> 5 -> null
Why: Slow moves one step, fast moves two steps to find middle faster
Step 3: Move slow by 1 step to node 3, fast by 2 steps to node 5
1 -> 2 -> [Slow->3] -> 4 -> [Fast->5] -> null
Why: Continue moving pointers until fast reaches the end
Step 4: Fast cannot move two steps further (end reached), stop
1 -> 2 -> [Slow->3] -> 4 -> 5 -> null
Fast at end
Why: Fast pointer reached the end, slow pointer is at middle
Result:
1 -> 2 -> [3] -> 4 -> 5 -> null
Middle element is 3
Annotated Code
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, val):
        new_node = Node(val)
        if not self.head:
            self.head = new_node
            return
        curr = self.head
        while curr.next:
            curr = curr.next
        curr.next = new_node

    def find_middle(self):
        slow = self.head
        fast = self.head
        while fast and fast.next:
            slow = slow.next  # advance slow by one
            fast = fast.next.next  # advance fast by two
        return slow.val if slow else None

# Driver code
ll = LinkedList()
for value in [1, 2, 3, 4, 5]:
    ll.append(value)
middle = ll.find_middle()
print(f"Middle element is {middle}")
slow = self.head fast = self.head
Initialize slow and fast pointers at the start of the list
while fast and fast.next:
Loop until fast pointer reaches the end or one before end
slow = slow.next # advance slow by one
Move slow pointer one step forward
fast = fast.next.next # advance fast by two
Move fast pointer two steps forward
return slow.val if slow else None
Return the value at slow pointer which is the middle
OutputSuccess
Middle element is 3
Complexity Analysis
Time: O(n) because we traverse the list once with the fast pointer moving twice as fast
Space: O(1) because we only use two pointers regardless of list size
vs Alternative: Naive approach counts nodes first then traverses again to middle, costing O(n) + O(n) = O(n), this method finds middle in one pass
Edge Cases
Empty list
Returns None since there is no middle
DSA Python
return slow.val if slow else None
List with one element
Returns the single element as middle
DSA Python
while fast and fast.next:
List with even number of elements
Returns the second middle element (e.g., for 4 elements returns 3rd node)
DSA Python
while fast and fast.next:
When to Use This Pattern
When you need to find the middle of a linked list in one pass, use two pointers moving at different speeds to find it efficiently.
Common Mistakes
Mistake: Moving both pointers by one step each time
Fix: Move fast pointer by two steps and slow pointer by one step to find middle in one pass
Mistake: Not checking if fast or fast.next is None before moving fast
Fix: Add condition 'while fast and fast.next' to avoid errors at list end
Summary
Finds the middle element of a linked list using two pointers moving at different speeds.
Use when you want the middle node without counting total nodes first.
The fast pointer moves twice as fast as the slow pointer, so when fast reaches the end, slow is in the middle.

Practice

(1/5)
1. What is the main idea behind finding the middle element of a singly linked list using the two-pointer technique?
easy
A. Use two pointers both moving one step at a time
B. Count all nodes first, then access the middle by index
C. Reverse the list and pick the first element
D. Use one slow pointer moving one step and one fast pointer moving two steps until fast reaches the end

Solution

  1. Step 1: Understand two-pointer movement

    The slow pointer moves one node at a time, while the fast pointer moves two nodes at a time.
  2. Step 2: Identify middle when fast pointer ends

    When the fast pointer reaches the end (null), the slow pointer will be at the middle node.
  3. Final Answer:

    Use one slow pointer moving one step and one fast pointer moving two steps until fast reaches the end -> Option D
  4. Quick Check:

    Two-pointer technique = slow one step, fast two steps [OK]
Hint: Move fast pointer twice as fast as slow to find middle [OK]
Common Mistakes:
  • Moving both pointers at the same speed
  • Counting nodes first instead of using pointers
  • Reversing the list unnecessarily
2. Which of the following Python code snippets correctly initializes pointers to find the middle of a linked list named head?
easy
A. slow = head\nfast = head
B. slow = head.next\nfast = head.next.next
C. slow = null\nfast = head
D. slow = head\nfast = null

Solution

  1. Step 1: Initialize both pointers at head

    To start traversal, both slow and fast pointers should begin at the head node.
  2. Step 2: Confirm correct initialization

    Setting slow = head and fast = head allows fast to move two steps and slow one step safely.
  3. Final Answer:

    slow = head\nfast = head -> Option A
  4. Quick Check:

    Both pointers start at head [OK]
Hint: Start both pointers at head node [OK]
Common Mistakes:
  • Starting slow or fast at null
  • Starting fast pointer too far ahead
  • Skipping initialization of pointers
3. What will be the output of the following code snippet that finds the middle element of a linked list?
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

def find_middle(head):
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow.val

# Creating linked list: 10 -> 20 -> 30 -> 40 -> 50
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)

print(find_middle(head))
medium
A. 30
B. 20
C. 40
D. 50

Solution

  1. Step 1: Trace pointer movements

    Initially, slow=10, fast=10. After first loop: slow=20, fast=30. Second loop: slow=30, fast=50. Third loop ends as fast.next is null.
  2. Step 2: Identify slow pointer value

    Slow pointer is at node with value 30 when loop ends, so 30 is middle.
  3. Final Answer:

    30 -> Option A
  4. Quick Check:

    Middle element = 30 [OK]
Hint: Slow pointer lands on middle when fast reaches end [OK]
Common Mistakes:
  • Returning fast pointer value instead of slow
  • Off-by-one errors in loop condition
  • Confusing node values during tracing
4. Identify the error in the following code that attempts to find the middle element of a linked list and fix it:
def find_middle(head):
    slow = head
    fast = head
    while fast.next and fast.next.next:
        slow = slow.next
        fast = fast.next.next
    return slow.val
medium
A. Return fast.val instead of slow.val
B. Change loop condition to 'while fast and fast.next' to avoid NoneType errors
C. Initialize slow and fast to null instead of head
D. Remove the loop entirely and return head.val

Solution

  1. Step 1: Analyze loop condition

    The condition 'while fast.next and fast.next.next' can cause an error if fast is null initially.
  2. Step 2: Correct loop condition

    Changing it to 'while fast and fast.next' ensures fast is not null before accessing fast.next.
  3. Final Answer:

    Change loop condition to 'while fast and fast.next' to avoid NoneType errors -> Option B
  4. Quick Check:

    Safe loop condition = while fast and fast.next [OK]
Hint: Check fast pointer is not null before accessing next [OK]
Common Mistakes:
  • Accessing fast.next without checking fast
  • Returning wrong pointer's value
  • Incorrect pointer initialization
5. Given a linked list with an even number of nodes, which node will the two-pointer method return as the middle?
For example, in the list 1 -> 2 -> 3 -> 4 -> null, what will be the middle element returned by the standard two-pointer approach?
hard
A. Node with value 2 (the first middle)
B. Node with value 1 (head node)
C. Node with value 3 (the second middle)
D. Node with value 4 (last node)

Solution

  1. Step 1: Trace pointers on even-length list

    Start: slow=1, fast=1. Loop 1: slow=2, fast=3. Loop 2: fast tries to move two steps but reaches end, loop stops.
  2. Step 2: Identify slow pointer position

    Slow pointer is at node with value 3 when loop ends, which is the second middle node.
  3. Final Answer:

    Node with value 3 (the second middle) -> Option C
  4. Quick Check:

    Two-pointer returns second middle in even list [OK]
Hint: Two-pointer method returns second middle in even-length lists [OK]
Common Mistakes:
  • Assuming it returns first middle node
  • Confusing head or last node as middle
  • Not tracing pointer steps carefully
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard