#1093
Medium Algorithms Statistics from a large sample
Array Math Probability and Statistics
43.0% acceptance
Feb 25, 2026
176
109
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.
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 within 10-5 of the actual answer will be accepted.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn sample_stats(count: Vec<i32>) -> Vec<f64> {
let mut minimum = -1i32;
let mut maximum = -1i32;
let mut total: i64 = 0;
let mut n: i64 = 0;
let mut mode = 0i32;
let mut mode_cnt = 0i32;
for (i, &c) in count.iter().enumerate() {
if c > 0 {
if minimum == -1 { minimum = i as i32; }
maximum = i as i32;
total += i as i64 * c as i64;
n += c as i64;
if c > mode_cnt { mode_cnt = c; mode = i as i32; }
}
}
let mean = total as f64 / n as f64;
// Median
let (m1, m2) = ((n + 1) / 2, (n + 2) / 2);
let mut cumulative = 0i64;
let mut med_vals = [0f64; 2];
let mut found = 0usize;
for (i, &c) in count.iter().enumerate() {
let prev = cumulative;
cumulative += c as i64;
for k in 0..2 {
let pos = if k == 0 { m1 } else { m2 };
if found <= k && prev < pos && pos <= cumulative {
med_vals[k] = i as f64;
found += 1;
}
}
if found == 2 { break; }
}
let median = (med_vals[0] + med_vals[1]) / 2.0;
vec![minimum as f64, maximum as f64, mean, median, mode as f64]
}
}