Average Salary Excluding the Minimum and Maximum Salary (LeetCode 1491): Solution and Explanation

Easy
Array
Sorting

Given unique salaries, return the average after dropping the single lowest and the single highest salary.

Intuition

An average is a sum divided by a count. Leaving out two salaries just means subtracting them from the sum and dividing by n - 2 instead of n.

You do not need to sort to know which two to leave out. The lowest and highest can be tracked while you add everything up.

Because the salaries are unique, there is exactly one minimum and one maximum, so subtracting each once is always right.

Approach: One pass for sum, min and max

  1. Set total = 0 and start lo and hi at the first salary.
  2. For each salary s: add it to total, lower lo if s is smaller, raise hi if s is larger.
  3. Return (total - lo - hi) / (n - 2) using floating point division.

Step-by-step example

salary = [4000,3000,1000,2000]
  1. 4000: total = 4000, lo = hi = 4000.
  2. 3000: total = 7000, lo = 3000. 1000: total = 8000, lo = 1000. 2000: total = 10000, lo and hi unchanged.
  3. Drop the extremes: 10000 - 1000 - 4000 = 5000.
  4. 5000 / 2 = 2500.0.

Code: Python, Java, C++

1class Solution:
2    def average(self, salary: List[int]) -> float:
3        total = 0
4        lo, hi = salary[0], salary[0]
5        for s in salary:
6            total += s
7            lo = min(lo, s)
8            hi = max(hi, s)
9        return (total - lo - hi) / (len(salary) - 2)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
One pass for sum, min and max O(n)
Built-in sum, min and max O(n)
Sort and slice O(n log n)
Time

O(n)

Each salary is visited once.

Space

O(1)

Only three running numbers are kept.

Other approaches

Sort and slice (time O(n log n), space O(1) to O(n))

Sort the array and average salary[1..n-2]. Simple, but sorting costs more than one pass.

Built-in sum, min and max (time O(n), space O(1))

In Python, (sum(s) - min(s) - max(s)) / (len(s) - 2) is three passes but still linear and very readable.

Common mistakes

  • Integer division. In Java, C++, C# and Go you must convert to double before dividing, or 5001 / 2 becomes 2500.
  • Dividing by n instead of n - 2.
  • Starting lo at 0 and hi at a small constant. Starting both at the first salary avoids picking a value that is not in the array.

Frequently asked questions

Can the sum overflow a 32-bit int?

No. At most 100 salaries of at most 1,000,000 add up to 100,000,000, well below 2^31 - 1.

What if salaries could repeat?

The problem would need to say whether to drop one copy or all copies of the extremes. As stated, you drop exactly one lowest and one highest value.

How precise must the answer be?

Within 10^-5 of the exact value, so normal double arithmetic is enough.