Problem 1491

Abstract / Summary

Calculate the average salary by excluding the lowest and highest values from a list of salaries.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1491.cpp

class Solution {
public:
    double average(vector<int>& salary) {
        sort(salary.begin(), salary.end());
        double result = 0;
        for (int i = 1; i < salary.size() - 1; i++)
            result += salary[i];
        result /= salary.size() - 2;
        return result;
    }
};
11 lines | 303 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the average salary after discarding the minimum and maximum values from a list of integers. It follows a straightforward approach: sorting the input, summing the interior elements, and dividing by the count of those elements. The function returns a double precision result, ensuring fractional values are represented accurately.

Key Steps

The first logical step is to arrange the salary values in non-decreasing order. This is achieved with a standard library sort call.

sort(salary.begin(), salary.end());

Sorting guarantees that the smallest element resides at index 0 and the largest at the last index, which simplifies the exclusion of these extremes.

The next step initializes an accumulator for the sum of the remaining salaries.

double result = 0;

A loop then iterates from the second element to the penultimate element, adding each value to the accumulator. The loop bounds deliberately skip the first and last positions.

for (int i = 1; i < salary.size() - 1; i++)
    result += salary[i];

After the accumulation, the total is divided by the number of elements that contributed to the sum. The divisor is the original size minus two, reflecting the removal of the minimum and maximum entries.

result /= salary.size() - 2;

Finally, the computed average is returned to the caller.

return result;

Edge Cases

The algorithm implicitly handles the situation where the input vector contains exactly three elements. After sorting, the loop runs once, adding the middle value, and the divisor becomes one, yielding the middle salary as the average. If the vector contains more than three elements, the loop aggregates all interior values, and the divisor adjusts accordingly. The use of double for the accumulator and the final division ensures that any fractional component of the average is preserved, even when the sum of integers does not divide evenly by the count.

Performance Optimizations

The code leverages the highly optimized std::sort algorithm, which typically employs introsort-a hybrid of quicksort, heapsort, and insertion sort-providing fast average-case performance while guarding against worst-case scenarios. By sorting once and then performing a single linear pass to compute the sum, the implementation avoids repeated scans or additional data structures. The accumulator is a double, eliminating the need for a separate conversion step after summation. The division is performed only once after the loop, minimizing arithmetic operations. Overall, the design balances clarity with efficient use of standard library facilities.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of cookies, and each cookie has a different number written on it. To find the average, you first line them all up from the smallest number to the biggest number so they look nice and neat. Once they are in a line, you take away the tiny cookie at the very start and the giant cookie at the very end. Setting those two aside means you only care about the cookies in the middle. You add up all the numbers on those remaining cookies to get one big total. To finish, you divide that total by how many cookies you kept, and that gives you the average number for the middle group.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.92 | σ = 1.36

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ Java C Go PHP Rust TS
Progiez Python C++ Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
35 links | 21 authors | 11 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality