Mean of Array After Removing Some Elements

The goal of this problem is to remove the smallest 5% and the largest 5% of elements from the array and then calculate the average of the remaining elements.

Here’s how we can approach this problem:

  1. First, we need to sort the array so that we can easily find the smallest and largest elements.
  2. Next, we calculate 5% of the array length to determine how many elements we need to remove from both ends of the sorted array. We use integer division (//) to make sure we get an integer result.
  3. We then slice the array to remove the smallest and largest elements. Python’s slicing feature makes this easy: arr[a:b] creates a new array from the a-th to (b-1)-th elements of arr.
  4. Finally, we calculate and return the average of the remaining elements.

Here is the Python code:

1
2
3
4
5
6
7
class Solution:
    def trimMean(self, arr: List[int]) -> float:
        arr.sort()
        n = len(arr)
        remove = n // 20  # find out how many elements we need to remove
        trimmed_arr = arr[remove:-remove]  # remove elements from both ends
        return sum(trimmed_arr) / len(trimmed_arr)  # calculate and return the average

This code first sorts the array, then removes the smallest and largest 5% of elements, and finally returns the average of the remaining elements. The average is calculated by dividing the sum of the elements by the number of elements.