We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Mean of Array After Removing Some Elements

Number: 1210

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given an integer array arr, remove the smallest 5% and largest 5% of the elements and return the mean of the remaining elements. The result is accepted if it is within 10⁻⁵ of the actual answer.


Key Insights

  • Sorting the array allows for straightforward identification and removal of the smallest and largest elements.
  • Since the array length is always a multiple of 20, exactly 5% of the elements from each end can be removed without rounding errors.
  • The mean is computed by summing the remaining values and dividing by their count.
  • The challenge mainly focuses on correct sorting and accurate slicing based on the percentage.

Space and Time Complexity

Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(n) depending on the sorting method used (or O(1) if sorting in-place).


Solution

The solution involves sorting the array so that the 5% smallest and 5% largest elements become easily accessible at the ends of the sorted array. Once sorted, calculate the number of elements to remove from each end (i.e., (5% * n)). Remove these elements by slicing the array and then compute the mean of the remaining elements by summing them and dividing by the number of elements left.


Code Solutions

# Python Solution
def trim_mean(arr):
    # Sort the array
    arr.sort()
    n = len(arr)
    # Calculate the number of elements to remove (5% from each end)
    trim_count = n * 5 // 100
    # Slice the array to remove the smallest and largest 5% of elements
    trimmed_arr = arr[trim_count:n - trim_count]
    # Calculate and return the mean of the remaining elements
    return sum(trimmed_arr) / len(trimmed_arr)

# Example usage:
if __name__ == "__main__":
    arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
    result = trim_mean(arr)
    print(result)  # Expected output: 4.00000
← Back to All Questions