Middle of the Linked List - 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.

Input & Output

Example 1 — Odd Length List
$ Input: head = [1,2,3,4,5]
Output: [3,4,5]
💡 Note: The middle node is 3. Since there's only one middle node in odd-length lists, return node 3 and all nodes after it.
Example 2 — Even Length List
$ Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
💡 Note: There are two middle nodes (3 and 4). Return the second middle node (4) and all nodes after it.
Example 3 — Single Node
$ Input: head = [1]
Output: [1]
💡 Note: Only one node exists, so it is the middle node.

Constraints

  • The number of nodes in the list is in the range [1, 100]
  • 1 ≤ Node.val ≤ 100

Visualization

Tap to expand
Middle of the Linked List INPUT Singly Linked List 1 2 3 4 5 null MIDDLE Input Parameters: head = [1,2,3,4,5] Length: 5 nodes Middle index: 2 (0-based) Return node at position 3 ALGORITHM STEPS Two Pointer (Slow/Fast) 1 Initialize Pointers slow = head, fast = head 2 Loop Condition while fast AND fast.next 3 Move Pointers slow += 1, fast += 2 4 Return Middle return slow (middle node) Pointer Trace: Step Slow Fast Init 1 1 1 2 3 2 3 5 End: slow at node 3 FINAL RESULT Middle Node and Rest: 3 4 5 null Output: [3, 4, 5] Starting from middle node OK - Verified! Complexity: Time: O(n) - single pass Space: O(1) - two pointers Key Insight: The fast pointer moves 2x speed of slow. When fast reaches end, slow is at middle. For even-length lists, this naturally returns the second middle node (as required). This "tortoise and hare" technique is useful for cycle detection and finding list midpoints. TutorialsPoint - Middle of the Linked List | Optimal Solution (Two Pointers)
Asked in
Google 25 Amazon 20 Microsoft 15 Apple 12
425.0K Views
High Frequency
~10 min Avg. Time
8.5K 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