Second Highest Salary — LeetCode 176 Python Solution

MediumDatabase
Problem
#176
Reading time
4 min

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_df

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(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.

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.

Get Stealth Interview