Ecommet

Middle of the Linked List

Easy Problem 51 of 151 Java and Python

Problem

Given the head of a singly linked list, return its middle node. If there are two middle nodes, return the second one.

Example 1

Input
head = [1, 2, 3, 4, 5]
Output
[3, 4, 5]
Why
Node 3 is the middle.

Example 2

Input
head = [1, 2, 3, 4, 5, 6]
Output
[4, 5, 6]
Why
Two middles (3 and 4): return the second.

Constraints

  • 1 ≤ number of nodes ≤ 100

Explanation

If one pointer moves twice as fast as another, the slow one is halfway when the fast one reaches the end.

Approach 1 · Naive

Count, then walk half

  • Time O(n), two passes
  • Space O(1)

Count the nodes in one pass, then walk count / 2 steps from the head.

  1. Count the nodes n.
  2. Walk n / 2 steps from head and return that node.
Java
class Solution {
    public ListNode middleNode(ListNode head) {
        int n = 0;
        for (ListNode node = head; node != null; node = node.next) {
            n++;
        }
        ListNode node = head;
        for (int i = 0; i < n / 2; i++) {
            node = node.next;
        }
        return node;
    }
}
Python
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        n, node = 0, head
        while node:
            n += 1
            node = node.next
        node = head
        for _ in range(n // 2):
            node = node.next
        return node

Approach 2 · Optimal

Slow and fast pointers

  • Time O(n), one pass
  • Space O(1)

Move slow one step and fast two steps until fast cannot move further.

  1. Set slow = fast = head.
  2. While fast and fast.next exist, move slow once and fast twice.
  3. Return slow.
Java
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
Python
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

Complexity compared

ApproachTimeSpace
Naive Count, then walk halfO(n), two passesO(1)
Optimal Slow and fast pointersO(n), one passO(1)

Key takeaways

  • To get the first middle instead, loop while fast.next and fast.next.next exist.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem