Mean of Array After Removing Some Elements - Problem

Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.

Answers within 10^-5 of the actual answer will be considered accepted.

Note: The percentage is calculated based on the original array length. For example, if the array has 20 elements, remove the smallest element (5% of 20 = 1) and the largest element.

Input & Output

Example 1 — Basic Case
$ 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
💡 Note: Array has 20 elements. Remove 5% = 1 element from each end. Remove smallest (1) and largest (3). Remaining 18 elements are all 2s, so mean = 2.0
Example 2 — Different Values
$ Input: arr = [6,2,7,5,1,2,10,8,5,8,2,6]
Output: 5.16667
💡 Note: 12 elements, remove 5% = 0.6 → 0 elements from each end. Keep all elements. Sum = 62, mean = 62/12 = 5.16667
Example 3 — Larger Array
$ 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,8,4,1,4,1,8,8,8,9,0,7,4,4,4,3,8,5,5,4,1,3,1]
Output: 4.77778
💡 Note: 60 elements, remove 5% = 3 elements from each end. After sorting, remove 3 smallest and 3 largest values. Calculate mean of remaining 54 elements.

Constraints

  • 20 ≤ arr.length ≤ 1000
  • arr.length is a multiple of 20
  • 0 ≤ arr[i] ≤ 105

Visualization

Tap to expand
Mean of Array After Removing Some Elements INPUT Array (20 elements): 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 = Remove (5% extremes) = Keep for mean Array Details Length: 20 elements 5% of 20 = 1 element Remove: smallest 1, largest 1 ALGORITHM STEPS 1 Sort Array Arrange in ascending order [1,2,2,2,...,2,2,3] 2 Calculate 5% n = 20, remove = 20 * 0.05 = 1 Remove 1 from each end 3 Trim Array Remove index 0 (value: 1) Remove index 19 (value: 3) 4 Calculate Mean Sum of remaining: 18 * 2 = 36 Count: 18 elements Mean = 36 / 18 = 2.0 Formula: mean = sum(arr[k:n-k]) / (n-2k) where k = floor(n * 0.05) FINAL RESULT Trimmed Array (18 elements): 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Calculation Sum = 2 x 18 = 36 Count = 18 Mean = 36 / 18 = 2.0 OUTPUT 2.00000 OK - ACCEPTED Key Insight: The Trimmed Mean is a robust statistic that reduces the impact of outliers. By removing the smallest and largest 5% of values, we get a more stable average. Sorting first ensures we correctly identify extreme values. Time Complexity: O(n log n) for sorting. TutorialsPoint - Mean of Array After Removing Some Elements | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
34.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen