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.00000
💡 Note: 12 elements, remove 5% = 0.6 → 0 elements from each end. Keep all elements. Sum = 60, mean = 60/12 = 5.0
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 After Removing 5% ExtremesExample: [6,2,7,5,1,2,10,8,5,8] → Sort → Remove extremes → Calculate meanStep 1: Original Array62751210858Step 2: Sort and Remove 5% from each end12255678810RemoveRemove10 elements → 5% = 0.5 → Remove 0 from each end (keep all)Step 3: Calculate MeanRemaining elements: [2,2,5,5,6,7,8,8]Sum = 2+2+5+5+6+7+8+8 = 43Mean = 43 ÷ 8 = 5.375
Understanding the Visualization
1
Input Array
Given integer array with various values
2
Sort and Remove
Sort array, remove 5% smallest and 5% largest elements
3
Calculate Mean
Sum remaining elements and divide by count
Key Takeaway
🎯 Key Insight: Sort first to easily identify and remove extreme values, then calculate mean of the stable middle range
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