These clues point to Fast and Slow Pointers: Move one pointer one step and another two steps; their meeting (or the fast one finishing) reveals cycles and middles.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
return slow;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
class Solution {
public ListNode middleNode(ListNode head) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) n++;
ListNode p = head;
for (int i = 0; i < n / 2; i++) p = p.next;
return p;
}
}
Verdict: Two passes; fine, but the next approach does it in one.
2
Optimal: fast and slow
Time O(n) Space O(1)
slow +1, fast +2 while fast and fast.next exist. Return slow.
Approach 2
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
Verdict: One pass.
Before you submit
Edge cases and common mistakes
Test these inputs
One node
Two nodes (returns the second)
Odd and even lengths
Mistakes people make
Loop condition fast.next.next != null returns the first middle for even lengths (the problem wants the second).
Interview
Follow-up questions
How would you return the first middle for even lengths?