Find Cumulative Salary of an Employee — LeetCode 579 Python Solution

HardLeetCode PremiumDatabase
Problem
#579
Reading time
3 min

Table schema

SQL
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

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

Python
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

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

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.

Get Stealth Interview