Problem Description
Given an array count of length 256 where count[k] represents the number of times the integer k appears in a sample (with k in the range [0, 255]), compute the following statistics for the sample:
- minimum: The smallest integer present.
- maximum: The largest integer present.
- mean: The average value of all integers.
- median: The middle value when the sample is sorted (or the average of the two middle values for an even number of elements).
- mode: The integer that appears the most (guaranteed to be unique).
Return these five statistics as an array of floating-point numbers.
Key Insights
- The sample is represented indirectly by counts, so there is no need to store the individual sample elements.
- The minimum and maximum can be obtained by scanning the count array for the first and last non-zero entries.
- The mean is calculated as the total sum of (value * frequency) divided by the total number of elements.
- The median is determined by using cumulative counts to find the middle element(s), handling even and odd total counts appropriately.
- The mode is the index with the highest frequency in the count array.
Space and Time Complexity
Time Complexity: O(256) ≈ O(1) since the count array size is fixed. Space Complexity: O(1) — only constant extra space is used.
Solution
We solve the problem by iterating through the count array once to compute basic statistics: the minimum, maximum, total sum of values, and the frequency of each number to determine the mode. After calculating the total number of elements, we use a second pass (or cumulative sum within the same loop) to identify the median. If the total count is odd, the median is the element at position total_count/2 + 1; if even, the median is the average of the two middle elements. This approach avoids reconstructing the full sample and efficiently computes the required statistics using constant extra space.