Median of a Sorted Array

Quick Overview

Compute the median of an integer array that is already sorted in non-decreasing order, returning a float for both odd and even lengths. It tests index arithmetic around the middle of an array, exact versus integer division, and averaging values that can be negative.

Median of a Sorted Array

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a sorted array `nums` of size `n`, return the median of the array. The median is the middle element of a sorted array. If `n` is odd, the median is the element at index `n // 2`. If `n` is even, the median is the average of the two middle elements. The returned value should be a floating point number. ### Function Signature ```python def find_median(nums: list[int]) -> float: ``` ### Rules - Indices are 0-based. - The average of the two middle elements uses exact division, so it can end in `.5`. - Return a float even when the median is a whole number, for example `3.0`. ### Constraints - `nums.length == n` - `1 <= n <= 1000` - `-10^6 <= nums[i] <= 10^6` - `nums` is sorted in non-decreasing order. ### Examples ```text Input: nums = [1, 2, 3, 4, 5] Output: 3.0 ``` The length is 5 (odd), so the median is the middle element `nums[2] = 3`. ```text Input: nums = [1, 2, 3, 4] Output: 2.5 ``` The length is 4 (even), so the median is `(nums[1] + nums[2]) / 2 = (2 + 3) / 2 = 2.5`. ```text Input: nums = [-7, -2, 1, 10] Output: -0.5 ``` The two middle elements are `-2` and `1`, so the median is `(-2 + 1) / 2 = -0.5`.

Overview: Compute the median of an integer array that is already sorted in non-decreasing order, returning a float for both odd and even lengths. It tests index arithmetic around the middle of an array, exact versus integer division, and averaging values that can be negative.

Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a sorted array nums of size n, return the median of the array.

The median is the middle element of a sorted array. If n is odd, the median is the element at index n // 2. If n is even, the median is the average of the two middle elements.

The returned value should be a floating point number.

Function Signature

def find_median(nums: list[int]) -> float:

Rules

  • Indices are 0-based.
  • The average of the two middle elements uses exact division, so it can end in .5 .
  • Return a float even when the median is a whole number, for example 3.0 .

Constraints

  • nums.length == n
  • 1 <= n <= 1000
  • -10^6 <= nums[i] <= 10^6
  • nums is sorted in non-decreasing order.

Examples

Input: nums = [1, 2, 3, 4, 5]
Output: 3.0

The length is 5 (odd), so the median is the middle element nums[2] = 3.

Input: nums = [1, 2, 3, 4]
Output: 2.5

The length is 4 (even), so the median is (nums[1] + nums[2]) / 2 = (2 + 3) / 2 = 2.5.

Input: nums = [-7, -2, 1, 10]
Output: -0.5

The two middle elements are -2 and 1, so the median is (-2 + 1) / 2 = -0.5.