Second Highest Salary — LeetCode 176 Python Solution
MediumDatabase
- Problem
- #176
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Return the second highest distinct salary in the Employee table, or null when the table does not hold two different salaries. Employee has id (int, primary key) and salary (int), one row per employee. The single output column is named SecondHighestSalary.
Example
- Input
- Employee(id, salary) = (1, 100), (2, 300), (3, 300), (4, 200)
- Output
- SecondHighestSalary = 200
- Explanation
- The distinct salaries are 300, 200 and 100, so the second highest is 200 — the duplicated 300 is not counted twice.
Python solution
Python
import pandas as pd
def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
# Drop any duplicate salary values to avoid counting duplicates as separate salary ranks
unique_salaries = employee["salary"].drop_duplicates()
# Sort the unique salaries in descending order and get the second highest salary
second_highest = (
unique_salaries.nlargest(2).iloc[-1] if len(unique_salaries) >= 2 else None
)
# If the second highest salary doesn't exist (e.g., there are fewer than two unique salaries), return None
if second_highest is None:
return pd.DataFrame({"SecondHighestSalary": [None]})
# Create a DataFrame with the second highest salary
result_df = pd.DataFrame({"SecondHighestSalary": [second_highest]})
return result_dfComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 176. Second Highest Salary?
- LeetCode 176. Second Highest Salary is rated Medium on LeetCode.
- What topics does LeetCode 176. Second Highest Salary cover?
- LeetCode 176. Second Highest Salary is tagged Database on LeetCode.