Median Employee Salary — LeetCode 569 Python Solution

HardLeetCode PremiumDatabase
Problem
#569
Reading time
2 min

Table schema

SQL
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

SQL
+--------------+---------+
| 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

Python
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

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

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.

Get Stealth Interview