Middle of List
Given an array representing a linked list, find the middle element. For odd-length arrays, return the exact middle element. For even-length arrays, return the element at index n/2 (the right middle in the two-pointer interpretation, or the left middle depending on convention).
For example, the middle of [1, 2, 3, 4, 5] is 3. The middle of [1, 2, 3, 4] is 3 (index 2 in 0-based indexing, which is length/2 = 4/2 = 2). The middle of [5] is 5. An empty array returns 0.
Finding the middle of a linked list is a classic problem that introduces the slow-and-fast pointer technique (also known as Floyd's tortoise and hare). A slow pointer moves one step at a time, while a fast pointer moves two steps. When the fast pointer reaches the end, the slow pointer is at the middle.
In an array, the middle is simply the element at index Math.floor(length / 2). However, the linked list version requires the two-pointer technique because you cannot access elements by index — you must traverse from the head. The two-pointer approach works in O(n) time with O(1) space, visiting each node at most once.
Edge cases include an empty array (return 0), a single-element array (return that element), and a two-element array (return the second element, index length/2 = 1).
Example Input & Output
Second middle for even
Middle of 5 elements
Three elements
Two elements
Single
Algorithm Flow
Solution Approach
Return the element at index Math.floor(arr.length / 2) for the array version.
For the array version, the middle index is Math.floor(length / 2). For odd lengths like 5, floor(5/2) = 2 (0-indexed: 0,1,2 — the third element is the middle). For even lengths like 4, floor(4/2) = 2 (0-indexed: 0,1,2,3 — indices 1 and 2 are the two middles; index 2 is the right middle).
For the linked list version using two pointers: initialize both slow and fast at the head. Move slow one step and fast two steps per iteration. When fast reaches the end, slow is at the middle.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int solution(int[] nums) {
return nums[nums.length/2];
}
}Related Linked List Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
