Skip to content

1619. Mean of Array After Removing Some Elements

  • Time: C++: $O(n)$, Java/Python: $O(|\texttt{sort}|)$
  • Space: C++: $O(1)$, Java/Python: $O(|\texttt{sort}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  double trimMean(vector<int>& arr) {
    int offset = arr.size() / 20;
    nth_element(arr.begin(), arr.begin() + offset, arr.end());
    nth_element(arr.begin() + offset, arr.end() - offset, arr.end());
    double sum = accumulate(arr.begin() + offset, arr.end() - offset, 0.0);
    return sum / (arr.size() - offset * 2);
  }
};
1
2
3
4
5
6
7
class Solution {
  public double trimMean(int[] arr) {
    Arrays.sort(arr);
    final int offset = arr.length / 20;
    return Arrays.stream(Arrays.copyOfRange(arr, offset, arr.length - offset)).average().orElse(0);
  }
}
1
2
3
4
5
class Solution:
  def trimMean(self, arr: list[int]) -> float:
    arr.sort()
    offset = len(arr) // 20
    return mean(arr[offset:-offset])