Middle of the Linked List - Problem

You're given the head of a singly linked list, and your task is to find and return the middle node of the list.

Here's the catch: if the linked list has an even number of nodes (meaning there are two potential middle nodes), you should return the second middle node.

Example: In a list with nodes [1,2,3,4,5], the middle node is 3. In a list with nodes [1,2,3,4,5,6], there are two middle nodes (3 and 4), so return node 4.

This is a classic problem that tests your understanding of linked list traversal and the elegant two-pointer technique!

Input & Output

example_1.py โ€” Odd Length List
$ Input: [1,2,3,4,5]
โ€บ Output: [3,4,5]
๐Ÿ’ก Note: The middle node is the 3rd node in the list (value 3). Return the node and all subsequent nodes.
example_2.py โ€” Even Length List
$ Input: [1,2,3,4,5,6]
โ€บ Output: [4,5,6]
๐Ÿ’ก Note: There are two middle nodes (3 and 4). Since we need the second middle node, return node 4 and all subsequent nodes.
example_3.py โ€” Single Node
$ Input: [1]
โ€บ Output: [1]
๐Ÿ’ก Note: With only one node, that node is both the head and the middle. Return the single node.

Visualization

Tap to expand
12345๐ŸขSLOW (1x)๐ŸฐFAST (2x)+1 each step+2 each stepFINISHTwo Pointers: When Fast Finishes, Slow is at Middle!๐ŸŽฏ RESULTSlow pointer (๐Ÿข) is at the middle node!Time: O(n), Space: O(1)
Understanding the Visualization
1
Start Together
Both slow (๐Ÿข) and fast (๐Ÿฐ) pointers begin at the head node
2
Different Speeds
In each step: slow moves 1 position, fast moves 2 positions
3
Fast Reaches End
When fast pointer reaches the end or goes beyond, slow is at middle
4
Perfect Positioning
The slow pointer is guaranteed to be at the middle (or second middle for even length)
Key Takeaway
๐ŸŽฏ Key Insight: The two-pointer technique guarantees that when the fast pointer (moving 2x speed) reaches the end, the slow pointer (moving 1x speed) will be exactly at the middle position. This works for both odd and even length lists!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Two traversals of the linked list: O(n) + O(n/2) = O(n)

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to store count and current position

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the list is in the range [1, 100]
  • 1 โ‰ค Node.val โ‰ค 100
Asked in
Amazon 45 Microsoft 35 Google 30 Meta 25
89.2K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen