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
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 medianCommon follow-up questions
- How would you find the median without sorting? (Tests quickselect algorithm for O(n) average-case median.)
- What if the data is streaming? (Tests the two-heap approach: max-heap for the lower half, min-heap for the upper half.)
- What is the difference between median and mean for skewed data? (Tests statistical reasoning about robustness to outliers.)