Average Salary Excluding the Minimum and Maximum Salary - Problem

You are given an array of unique integers salary where salary[i] is the salary of the i-th employee.

Return the average salary of employees excluding the minimum and maximum salary. Answers within 10^-5 of the actual answer will be accepted.

Input & Output

Example 1 — Basic Case
$ Input: salary = [4000,3000,1000,2000]
Output: 2500.0
💡 Note: Minimum salary is 1000, maximum salary is 4000. Average of remaining salaries: (3000 + 2000) / 2 = 2500.0
Example 2 — Minimum Size
$ Input: salary = [1000,2000,3000]
Output: 2000.0
💡 Note: Minimum salary is 1000, maximum salary is 3000. Average of remaining salaries: 2000 / 1 = 2000.0
Example 3 — Larger Array
$ Input: salary = [8000,9000,2000,3000,6000,1000]
Output: 4750.0
💡 Note: Minimum salary is 1000, maximum salary is 9000. Average of remaining: (8000+2000+3000+6000) / 4 = 4750.0

Constraints

  • 3 ≤ salary.length ≤ 100
  • 1000 ≤ salary[i] ≤ 106
  • All the integers of salary are unique

Visualization

Tap to expand
Average Salary Excluding Min/Max INPUT salary array (4 employees) 4000 i=0 3000 i=1 1000 i=2 MIN 2000 i=3 MAX Input Values salary = [4000, 3000, 1000, 2000] n = 4 employees All values unique ALGORITHM STEPS 1 Initialize Trackers min=INF, max=-INF, sum=0 2 Single Pass Scan Track min, max, total sum Val Min Max Sum 4000 4000 4000 4000 3000 3000 4000 7000 1000 1000 4000 8000 2000 1000 4000 10000 3 Subtract Extremes 10000 - 1000 - 4000 = 5000 4 Calculate Average 5000 / (4-2) = 2500.0 FINAL RESULT Excluded values: 1000 4000 Included values: 3000 2000 Average Calculation: (3000 + 2000) / 2 = 5000 / 2 OUTPUT 2500.0 Key Insight: Single pass approach achieves O(n) time complexity by tracking min, max, and sum simultaneously. Instead of sorting O(n log n), we subtract extremes from total: avg = (sum - min - max) / (n - 2). This works because we only need to exclude exactly one minimum and one maximum value. TutorialsPoint - Average Salary Excluding the Minimum and Maximum Salary | Single Pass with Min/Max Tracking
Asked in
Apple 15 Microsoft 12
66.7K Views
Medium Frequency
~15 min Avg. Time
1.9K 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