Mean of Array After Removing Some Elements
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer array arr, return the mean of the remaining integers after removing the smallest5% and the largest 5% of the elements.
Answers within 10-5 of the actual answer will be considered accepted.
Examples
Example 1
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
Example 2
Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
Output: 4.00000
Example 3
Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
Output: 4.77778
Constraints
20 <= arr.length <= 1000arr.length****is a multiple of20.0 <= arr[i] <= 10^5
Solution
Method 1 – Sorting and Slicing
Intuition
To remove the smallest and largest 5% of elements, sort the array and slice off the required number of elements from both ends. The mean of the remaining elements is the answer.
Approach
- Sort the array.
- Compute
k = n // 20(5% of the array size). - Remove the first
kand lastkelements. - Calculate the mean of the remaining elements.
- Return the mean as a float.
Code
C++
class Solution {
public:
double trimMean(vector<int>& arr) {
int n = arr.size(), k = n / 20;
sort(arr.begin(), arr.end());
double sum = 0;
for (int i = k; i < n - k; ++i) sum += arr[i];
return sum / (n - 2 * k);
}
};
Go
func trimMean(arr []int) float64 {
n := len(arr)
k := n / 20
sort.Ints(arr)
sum := 0
for i := k; i < n-k; i++ {
sum += arr[i]
}
return float64(sum) / float64(n-2*k)
}
Java
class Solution {
public double trimMean(int[] arr) {
int n = arr.length, k = n / 20;
Arrays.sort(arr);
double sum = 0;
for (int i = k; i < n - k; i++) sum += arr[i];
return sum / (n - 2 * k);
}
}
Kotlin
class Solution {
fun trimMean(arr: IntArray): Double {
val n = arr.size
val k = n / 20
arr.sort()
var sum = 0.0
for (i in k until n - k) sum += arr[i]
return sum / (n - 2 * k)
}
}
Python
def trim_mean(arr: list[int]) -> float:
n = len(arr)
k = n // 20
arr.sort()
return sum(arr[k:n-k]) / (n - 2 * k)
Rust
impl Solution {
pub fn trim_mean(arr: Vec<i32>) -> f64 {
let n = arr.len();
let k = n / 20;
let mut arr = arr;
arr.sort();
let sum: i32 = arr[k..n-k].iter().sum();
sum as f64 / (n - 2 * k) as f64
}
}
TypeScript
class Solution {
trimMean(arr: number[]): number {
const n = arr.length, k = Math.floor(n / 20);
arr.sort((a, b) => a - b);
let sum = 0;
for (let i = k; i < n - k; ++i) sum += arr[i];
return sum / (n - 2 * k);
}
}
Complexity
- ⏰ Time complexity:
O(n log n), due to sorting the array. - 🧺 Space complexity:
O(1)(in-place sort), orO(n)if not in-place.