Code Logo

Compute Median

Published at25 Jul 2026
Statistics Easy 0 views
Like0

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

Example 1
Input
[1,2,3,4]
Output
2
Explanation

Median of sorted even-length is lower middle

Example 2
Input
[5]
Output
5
Explanation

Single

Example 3
Input
[1,2,3,4,5,6]
Output
3
Explanation

Lower median for even

Example 4
Input
[10,20,30,40]
Output
20
Explanation

Lower median

Example 5
Input
[1,2,3,4,5]
Output
3
Explanation

Median of sorted odd-length

Algorithm Flow

Recommendation Algorithm Flow for Compute Median
Recommendation Algorithm Flow for Compute Median

Solution Approach

Compute the index using integer division and return the element at that position.

function solution(arr) {
  if (arr.length === 0) return 0;
  return arr[Math.floor((arr.length - 1) / 2)];
}

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

java
class Solution {
    public int solution(int[] nums) {
        return nums.length>0?nums[(nums.length-1)/2]:0;
    }
}