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;
}
};
Difficulty
and has an acceptance rate of about 64% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Sorting
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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