You are given an integer array arr
consisting of n
elements, where n
is divisible by 20. Remove the smallest 5% and the largest 5% of the elements in the array. After removing those elements, find the mean of the remaining elements.
Input: arr = [1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 100, 200, 300, 400, 500, 600, 700, 800, 900]
Output: 200.78947
arr
: We know that n
is divisible by 20. This means the array size will always be a multiple of 20.n/20
. Remove these elements from both ends of the sorted array.Overall, the time complexity is dominated by the sorting step, which is (O(n \log n)).
def trimMean(arr):
arr.sort()
n = len(arr)
remove_count = n // 20 # 5% of the array length
trimmed_arr = arr[remove_count:-remove_count] # Removing 5% smallest and largest
# Calculate mean
mean_value = sum(trimmed_arr) / len(trimmed_arr)
return mean_value
arr = [1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 100, 200, 300, 400, 500, 600, 700, 800, 900]
result = trimMean(arr)
print(result) # Output: 200.78947
This code takes an array, removes the smallest and largest 5% of its elements after sorting, and then calculates and returns the mean of the remaining elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?