#176
Second Highest Salary
MediumDatabaseSubqueriesAggregate Functions
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)
Instead of comparing every salary, we can use a subquery to directly find the maximum salary that is less than the overall maximum salary, which is much more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Use a subquery to find the maximum salary from the Employee table.
- 2Step 2: In the outer query, find the maximum salary that is less than the result of the subquery.
- 3Step 3: If there is no such salary, the result will be null.
solution.py3 lines
1SELECT MAX(salary) AS SecondHighestSalary
2FROM Employee
3WHERE salary < (SELECT MAX(salary) FROM Employee);ℹ
Complexity note: This complexity is linear because we only need to scan through the salaries twice: once for the maximum and once for the second maximum.
- 1Using subqueries can significantly reduce the number of comparisons needed.
- 2Understanding how to use aggregate functions like MAX() is crucial for efficient SQL queries.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.