MediumNo. 0177

Nth Highest Salary — LeetCode 177 Python Solution

Topics
Database
Reading time
3 min

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0176Second Highest SalaryMedium
0178Rank ScoresMedium
0175Combine Two TablesEasy
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy
0182Duplicate EmailsEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.