Problem
You are given a large sample of integers in the range [0, 255]
. Since the sample is so large, it is represented by an array count
where count[k]
is the number of times that k
appears in the sample.
Calculate the following statistics:
minimum
: The minimum element in the sample.maximum
: The maximum element in the sample.mean
: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.median
:- If the sample has an odd number of elements, then the
median
is the middle element once the sample is sorted. - If the sample has an even number of elements, then the
median
is the average of the two middle elements once the sample is sorted.
- If the sample has an odd number of elements, then the
mode
: The number that appears the most in the sample. It is guaranteed to be unique.
Return the statistics of the sample as an array of floating-point numbers[minimum, maximum, mean, median, mode]
. Answers within10-5
of the actual answer will be accepted.
Examples
Example 1
|
|
Example 2
|
|
Constraints
count.length == 256
0 <= count[i] <= 10^9
1 <= sum(count) <= 10^9
- The mode of the sample that
count
represents is unique.
Solution
Method 1 -
Method 1 – Prefix Sums and Counting
Intuition
Since the sample is represented by a frequency array, we can efficiently compute statistics by scanning through the array and using prefix sums to find the mean, median, and mode. The median can be found by walking through the counts and tracking the cumulative frequency.
Approach
- Initialize variables for minimum, maximum, total sum, total count, and mode.
- Iterate through the count array:
- For each value, if its count is nonzero, update minimum and maximum.
- Add to the total sum and total count.
- Track the mode by keeping the value with the highest count.
- Compute the mean as total sum divided by total count.
- To find the median:
- Walk through the count array, accumulating frequencies.
- For odd total count, find the middle value.
- For even total count, find the two middle values and average them.
- Return the statistics as a float array:
[minimum, maximum, mean, median, mode]
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(256)
— We scan the count array a constant number of times. - 🧺 Space complexity:
O(1)
— Only a fixed number of variables are used for statistics.