HardNo. 0569LeetCode Premium

Median Employee Salary — LeetCode 569 Python Solution

Topics
Database
Reading time
2 min

Table schema

SQLTable schema
Table: Employee +--------------+---------+ | Column Name | Type | +--------------+---------+ | id | int | | company | varchar | | salary | int | +--------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table indicates the company and the salary of one employee.

Example

SQLExample
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| id           | int     |
| company      | varchar |
| salary       | int     |
+--------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the company and the salary of one employee.

Python solution

PythonSolution
import pandas as pd

def median_employee_salary(employee: pd.DataFrame) -> pd.DataFrame:
    df = employee.sort_values(['company', 'salary', 'id'])
    df['rn'] = df.groupby('company').cumcount() + 1
    df['cnt'] = df.groupby('company')['id'].transform('count')
    low = (df['cnt'] + 1) // 2
    high = (df['cnt'] + 2) // 2
    res = df[(df['rn'] >= low) & (df['rn'] <= high)]
    return res[['id', 'company', 'salary']]

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0570Managers with at Least 5 Direct ReportsMedium
0577Employee BonusEasy
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium

Frequently asked questions

How hard is LeetCode 569. Median Employee Salary?

LeetCode 569. Median Employee Salary is rated Hard on LeetCode.

What topics does LeetCode 569. Median Employee Salary cover?

LeetCode 569. Median Employee Salary is tagged Database on LeetCode.

Is LeetCode 569. Median Employee Salary a premium problem?

Yes. LeetCode 569. Median Employee Salary is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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.