Group Employees of the Same Salary — LeetCode 1875 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1875
Reading time
4 min

Table schema

SQL
Table: Employees +-------------+---------+ | Column Name | Type | +-------------+---------+ | employee_id | int | | name | varchar | | salary | int | +-------------+---------+ employee_id is the column with unique values for this table. Each row of this table indicates the employee ID, employee name, and salary.

Example

SQL
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| employee_id | int     |
| name        | varchar |
| salary      | int     |
+-------------+---------+
employee_id is the column with unique values for this table.
Each row of this table indicates the employee ID, employee name, and salary.

Python solution

Python
import duckdb
import pandas as pd

def solution(employees: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Employees", employees)
    return con.execute("""WITH
    S AS (
        SELECT salary
        FROM Employees
        GROUP BY salary
        HAVING COUNT(1) > 1
    ),
    T AS (
        SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS team_id
        FROM S
    )
SELECT e.*, t.team_id
FROM
    Employees AS e
    JOIN T AS t ON e.salary = t.salary
ORDER BY 4, 1;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1875. Group Employees of the Same Salary?
LeetCode 1875. Group Employees of the Same Salary is rated Medium on LeetCode.
What topics does LeetCode 1875. Group Employees of the Same Salary cover?
LeetCode 1875. Group Employees of the Same Salary is tagged Database on LeetCode.
Is LeetCode 1875. Group Employees of the Same Salary a premium problem?
Yes. LeetCode 1875. Group Employees of the Same 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