The Halftime Score

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4
Asked in
Apple

Problem

Given a non-empty list of numbers, return its median. For even length, return the average of the two middle values. Do not rely on external libraries.

Middle value of a dataset. No built-in shortcuts.

Example 1

Input:

nums = [3,1,2]

Output:

2

Example 2

Input:

nums = [1,2,3,4]

Output:

2.5

Worked solution and explanation

Why this problem exists in real interviews

This tests median computation without library functions, probing whether a candidate understands the definition of median and can handle both odd and even list lengths.


Break down the requirements

Step 1: Sort the list

The median requires ordered data.

Step 2: Handle odd and even lengths

Odd: return the middle element. Even: return the average of the two middle elements.


The solution

Sort and select median
def compute_median(nums: list) -> float:
    sorted_nums = sorted(nums)
    n = len(sorted_nums)
    if n % 2 == 1:
        median = float(sorted_nums[n // 2])
    else:
        left = sorted_nums[n // 2 - 1]
        right = sorted_nums[n // 2]
        median = (left + right) / 2.0
    return median

Common follow-up questions