HardNo. 0579LeetCode Premium

Find Cumulative Salary of an Employee — LeetCode 579 Python Solution

Topics
Database
Reading time
3 min

Table schema

SQLTable schema
Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | month | int | | salary | int | +-------------+------+ (id, month) is the primary key (combination of columns with unique values) for this table. Each row in the table indicates the salary of an employee in one month during the year 2020.

Example

SQLExample
+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| month       | int  |
| salary      | int  |
+-------------+------+
(id, month) is the primary key (combination of columns with unique values) for this table.
Each row in the table indicates the salary of an employee in one month during the year 2020.

Python solution

PythonSolution
import pandas as pd

def cumulative_salary(employee: pd.DataFrame) -> pd.DataFrame:
    df = employee.sort_values(['id', 'month'])
    df['rolling'] = (
        df.groupby('id')['salary']
          .rolling(3, min_periods=1)
          .sum()
          .reset_index(level=0, drop=True)
    )
    max_month = df.groupby('id')['month'].transform('max')
    res = df[df['month'] < max_month][['id', 'month', 'rolling']]
    res = res.rename(columns={'rolling': 'salary'})
    return res

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 579. Find Cumulative Salary of an Employee?

LeetCode 579. Find Cumulative Salary of an Employee is rated Hard on LeetCode.

What topics does LeetCode 579. Find Cumulative Salary of an Employee cover?

LeetCode 579. Find Cumulative Salary of an Employee is tagged Database on LeetCode.

Is LeetCode 579. Find Cumulative Salary of an Employee a premium problem?

Yes. LeetCode 579. Find Cumulative Salary of an Employee 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.