KatInterview

Compute Safe Summary Statistics for Numeric Series

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaps-sortingarraysmath-bits

Last 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:

  1. Empty Input: If nums is empty, return a dictionary where all three statistic keys mapping to None: {"min": None, "mean": None, "median": None}.
  2. Invalid Entries: If any element in nums is None or a floating-point NaN value (checked via math.isnan), raise a ValueError.
  3. 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.