Compute Median
Given a sorted array of integers, find the median. For odd-length arrays, the median is the middle element. For even-length arrays, return the lower middle element (the element at index (n/2) - 1, where n is the length).
For example, the sorted array [1, 2, 3, 4, 5] has median 3 (the middle element). The array [1, 2, 3, 4] has median 2 (the lower of the two middle values). A single-element array [5] has median 5. For an empty array, return 0.
The median is a measure of central tendency that is more robust to outliers than the mean. For skewed distributions (like income data), the median often gives a more representative typical value. In computing, median finding is used in image processing (median filter for noise reduction), statistics packages, and data analysis pipelines.
For an already-sorted array, the median is simply the element at index floor((n-1)/2), which works for both odd and even lengths. This is because integer division truncates downward: for n = 5, (5-1)//2 = 2 (the middle); for n = 4, (4-1)//2 = 1 (the lower middle).
The challenge guarantees the array is sorted ascending, so your solution does not need to sort it. Simply compute the index and return the element at that position. Edge cases include an empty array (return 0) and a single-element array (return that element).
Example Input & Output
Median of sorted even-length is lower middle
Single
Lower median for even
Lower median
Median of sorted odd-length
Algorithm Flow

Solution Approach
Compute the index using integer division and return the element at that position.
The formula (length - 1) // 2 gives the correct median index for a sorted array. For odd lengths, it selects the exact middle: (5-1)//2 = 2, which is the third element (index 2). For even lengths, it selects the lower middle: (4-1)//2 = 1, which is the second element. This works because integer division truncates the fractional part.
If the array is empty, the function returns 0 immediately to avoid accessing an invalid index. For a single element, (1-1)//2 = 0, returning the only element.
Time complexity is O(1) since array access by index is constant time. Space complexity is O(1). The array is assumed to be pre-sorted, so no sorting cost is incurred.
Best Answers
class Solution {
public int solution(int[] nums) {
return nums.length>0?nums[(nums.length-1)/2]:0;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
