The Number of Seniors and Juniors to Join the Company — LeetCode 2004 Python Solution

HardLeetCode PremiumDatabase
Problem
#2004
Reading time
7 min

Table schema

SQL
Table: Candidates +-------------+------+ | Column Name | Type | +-------------+------+ | employee_id | int | | experience | enum | | salary | int | +-------------+------+ employee_id is the column with unique values for this table. experience is an ENUM (category) type of values ('Senior', 'Junior').

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| employee_id | int  |
| experience  | enum |
| salary      | int  |
+-------------+------+
employee_id is the column with unique values for this table.
experience is an ENUM (category) type of values ('Senior', 'Junior').
Each row of this table indicates the id of a candidate, their monthly salary, and their experience.

Python solution

Python
import duckdb
import pandas as pd

def solution(candidates: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Candidates", candidates)
    return con.execute("""WITH
    s AS (
        SELECT
            employee_id,
            SUM(salary) OVER (ORDER BY salary) AS cur
        FROM Candidates
        WHERE experience = 'Senior'
    ),
    j AS (
        SELECT
            employee_id,
            IFNULL(
                SELECT
                    MAX(cur)
                FROM s
                WHERE cur <= 70000,
                0
            ) + SUM(salary) OVER (ORDER BY salary) AS cur
        FROM Candidates
        WHERE experience = 'Junior'
    )
SELECT
    'Senior' AS experience,
    COUNT(employee_id) AS accepted_candidates
FROM s
WHERE cur <= 70000
UNION ALL
SELECT
    'Junior' AS experience,
    COUNT(employee_id) AS accepted_candidates
FROM j
WHERE cur <= 70000;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 2004. The Number of Seniors and Juniors to Join the Company?
LeetCode 2004. The Number of Seniors and Juniors to Join the Company is rated Hard on LeetCode.
What topics does LeetCode 2004. The Number of Seniors and Juniors to Join the Company cover?
LeetCode 2004. The Number of Seniors and Juniors to Join the Company is tagged Database on LeetCode.
Is LeetCode 2004. The Number of Seniors and Juniors to Join the Company a premium problem?
Yes. LeetCode 2004. The Number of Seniors and Juniors to Join the Company 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