In this tutorial, we explore two approaches to find the middle node of a singly linked list: the brute force method and the efficient fast-slow pointer technique (also known as the Tortoise and Hare algorithm). This classic interview problem is essential for understanding linked list traversal and two-pointer strategies.
Brute Force Approach
The brute force method involves two passes: first, count the total number of nodes in the list; second, traverse again to the middle node. While simple, this approach has time complexity O(n) and space complexity O(1). It is straightforward but requires two passes.
Fast & Slow Pointer Approach
The fast-slow pointer technique uses two pointers: a slow pointer that moves one step at a time, and a fast pointer that moves two steps. When the fast pointer reaches the end, the slow pointer is at the middle. This single-pass algorithm also runs in O(n) time and O(1) space, making it both efficient and elegant.
Step-by-Step Dry Run
- Initialize both pointers at the head.
- Move slow by one and fast by two until fast reaches the end or the last node.
- The node pointed by slow is the middle.
Edge Cases and Interview Tips
- For an even number of nodes, the algorithm returns the first middle node (if using standard while condition).
- Always handle empty list and single node cases.
- The Tortoise and Hare technique extends to cycle detection, palindrome checking, and finding the nth node from the end.
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Brute Force | O(n) | O(1) |
| Fast & Slow Pointer | O(n) | O(1) |
Code Examples
Solutions are provided in Python, Java, and C++, making this tutorial accessible to developers across languages.
Master this fundamental problem to strengthen your interview preparation for linked list questions.