#1491
Average Salary Excluding the Minimum and Maximum Salary
EasyArraySortingArrayMathematical Aggregation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution improves on the brute-force approach by calculating the total sum in a single pass while simultaneously finding the minimum and maximum salaries. This reduces the number of iterations needed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize variables for total sum, minimum salary, and maximum salary.
- 2Step 2: Iterate through the salary array to compute total sum, minimum, and maximum in one pass.
- 3Step 3: Subtract the minimum and maximum from the total sum.
- 4Step 4: Divide the result by the number of salaries minus 2 to get the average.
solution.py13 lines
1# Full working Python code
2
3def average_salary(salary):
4 total_sum = 0
5 min_salary = float('inf')
6 max_salary = float('-inf')
7
8 for s in salary:
9 total_sum += s
10 min_salary = min(min_salary, s)
11 max_salary = max(max_salary, s)
12
13 return (total_sum - min_salary - max_salary) / (len(salary) - 2)ℹ
Complexity note: The time complexity is O(n) because we only loop through the array once to calculate the total sum, minimum, and maximum salaries. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Understanding how to efficiently calculate aggregates (sum, min, max) in a single pass can significantly improve performance.
- 2Recognizing that the constraints guarantee unique salaries simplifies the problem, as we don't need to handle duplicates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.