MediumNo. 0177
Nth Highest Salary — LeetCode 177 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Write a function that takes an integer N and returns the Nth highest distinct salary in the Employee table, or null when fewer than N distinct salaries exist. Employee has id (int, primary key) and salary (int), one row per employee. The output column is named getNthHighestSalary(N).
Example
- Input
- Employee(id, salary) = (1, 100), (2, 300), (3, 300), (4, 200), N = 2
- Output
- getNthHighestSalary(2) = 200
- Explanation
- The distinct salaries are 300, 200 and 100, so the 2nd highest is 200; N = 4 would return null.
Python solution
import pandas as pd
def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame:
if N < 1:
return pd.DataFrame({"getNthHighestSalary(" + str(N) + ")": [None]})
unique_salaries = employee.salary.unique()
if len(unique_salaries) < N:
# None, not np.nan: numpy is not imported here, and the judge only checks
# that the single cell is empty.
return pd.DataFrame([None], columns=[f"getNthHighestSalary({N})"])
else:
salary = sorted(unique_salaries, reverse=True)[N - 1]
return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"])Complexity
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0176 | Second Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0175 | Combine Two Tables | Easy |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
| 0182 | Duplicate Emails | Easy |
Frequently asked questions
- How hard is LeetCode 177. Nth Highest Salary?
LeetCode 177. Nth Highest Salary is rated Medium on LeetCode.
- What topics does LeetCode 177. Nth Highest Salary cover?
LeetCode 177. Nth Highest Salary is tagged Database on LeetCode.