Compute Safe Summary Statistics for Numeric Series
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Computes min, mean, and median robustly for floating-point data, handling missing/invalid values and large magnitude edge cases safely.
Write a function robust_stats that accepts a list of numerical values and computes three standard descriptive statistics: the minimum, the arithmetic mean, and the median.
The function must adhere to the following rules and error handling policies:
- Empty Input: If
numsis empty, return a dictionary where all three statistic keys mapping toNone:{"min": None, "mean": None, "median": None}. - Invalid Entries: If any element in
numsisNoneor a floating-pointNaNvalue (checked viamath.isnan), raise aValueError. - Valid Non-Empty Input: Return a dictionary containing the computed statistics:
{"min": min_val, "mean": mean_val, "median": median_val}.- Minimum: The smallest element present in the input.
- Mean: The arithmetic average computed using an online numerical approach to prevent overflow when summing extremely large numbers.
- Median: The middle element when sorted. If the number of elements $N$ is odd, return the element at index $N // 2$. If $N$ is even, return the average of the elements at indices $N // 2 - 1$ and $N // 2$. To avoid floating-point overflow, average two values $a$ and $b$ using $a / 2 + b / 2$.
Constraints
- $0 \le \text{len}(nums) \le 10^5$
- Elements can be positive, negative, or zero floats/integers.
- $N = \text{len}(nums)$
Examples
Example 1
Input: robust_stats([3, 1, 2])
Output: {'min': 1, 'mean': 2, 'median': 2}
Example 2
Input: robust_stats([1, 2, 3, 4])
Output: {'min': 1, 'mean': 2.5, 'median': 2.5}
Example 3
Input: robust_stats([])
Output: {'min': None, 'mean': None, 'median': None}
Hints
Hint 1
Check for empty input and invalid elements (None or NaN) before starting calculations.
Hint 2
To compute the mean safely without total sum overflow, update the running mean iteratively: mean += (x - mean) / i for the i-th element.
Hint 3
Quickselect or sorting can be used for finding the median. Be sure to avoid mutating the original input array.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To reliably compute the statistics under strict numerical stability constraints and validation rules:
-
Validation & Edge Cases:
- First, check if the input array
numsis empty. If so, return{"min": None, "mean": None, "median": None}. - Check every element for invalid entries (
Noneormath.isnan(x)). If any exist, raise aValueError.
- First, check if the input array
-
Minimum & Mean:
- We track the minimum element in a single pass.
- Computing the sum directly via
sum(nums)can cause numeric overflow if elements are near float capacity (e.g., $10^{308}$). Instead, we use Welford's online mean formula: $$\mu_i = \mu_{i-1} + \frac{x_i - \mu_{i-1}}{i}$$ This keeps the running statistic at the magnitude scale of the input values.
-
Median via Quickselect:
- We make a shallow copy of
numsto avoid mutating the original input. - We use an iterative Quickselect algorithm with Dutch National Flag 3-way partitioning to find the $k$-th order statistic. 3-way partitioning ensures $O(N)$ performance even in the presence of numerous duplicate values.
- If the input length $N$ is odd, the median is the value at index $N // 2$.
- If $N$ is even, we retrieve the values at $N // 2 - 1$ and $N // 2$, returning
lower / 2.0 + upper / 2.0to avoid potential overflow during summation.
- We make a shallow copy of
Complexity
- Time Complexity:
- Minimum and Mean: $O(N)$ single-pass computation.
- Median: $O(N)$ average time complexity using Quickselect ($O(N^2)$ worst-case if pivots are poorly chosen, though mitigated by middle-element pivot selection and 3-way partition). Alternatively, sorting takes $O(N \log N)$.
- Total Time Complexity: $O(N)$ expected.
- Space Complexity: $O(N)$ auxiliary space to create a mutable copy of the input list.
Python Reference Solution
import math
from typing import Dict, List, Optional
def robust_stats(nums: List[float]) -> Dict[str, Optional[float]]:
if not nums:
return {"min": None, "mean": None, "median": None}
if any(x is None or (isinstance(x, float) and math.isnan(x)) for x in nums):
raise ValueError("nums must contain only non-NaN numbers")
minimum = nums[0]
mean = 0.0
for i, x in enumerate(nums, 1):
if x < minimum:
minimum = x
mean += (x - mean) / i
values = list(nums)
n = len(values)
def select(k: int) -> float:
left, right = 0, n - 1
while left <= right:
pivot = values[(left + right) // 2]
less, current, greater = left, left, right
while current <= greater:
if values[current] < pivot:
values[less], values[current] = values[current], values[less]
less += 1
current += 1
elif values[current] > pivot:
values[current], values[greater] = values[greater], values[current]
greater -= 1
else:
current += 1
if k < less:
right = less - 1
elif k > greater:
left = greater + 1
else:
return values[k]
raise RuntimeError("selection failed")
if n % 2 != 0:
median = select(n // 2)
else:
lower = select(n // 2 - 1)
upper = select(n // 2)
median = lower / 2.0 + upper / 2.0
return {"min": minimum, "mean": mean, "median": median}