Human Traffic of Stadium — LeetCode 601 Python Solution

HardDatabase
Problem
#601
Reading time
2 min

The problem

Report the rows that belong to a stretch of three or more consecutive ids in which every day drew at least 100 visitors, ordered by visit date. The Stadium table has one row per day: id (int), visit_date (date, the column with unique values) and people (int, the number of visitors that day). The id grows together with the date.

Example

Stadium table:

| id | visit_date | people |
| -- | ---------- | ------ |
| 1  | 2024-07-01 | 145    |
| 2  | 2024-07-02 | 80     |
| 3  | 2024-07-03 | 210    |
| 4  | 2024-07-04 | 190    |
| 5  | 2024-07-05 | 155    |
| 6  | 2024-07-06 | 95     |

Result:

| id | visit_date | people |
| -- | ---------- | ------ |
| 3  | 2024-07-03 | 210    |
| 4  | 2024-07-04 | 190    |
| 5  | 2024-07-05 | 155    |

Ids 3, 4 and 5 form a run of three busy days; id 1 is busy but isolated, and ids 2 and 6 fall under 100.

Python solution

Python
import pandas as pd

def human_traffic(stadium: pd.DataFrame) -> pd.DataFrame:
    df = stadium[stadium['people'] >= 100].sort_values('id')
    df['grp'] = (df['id'].diff() != 1).cumsum()
    sizes = df.groupby('grp')['id'].transform('count')
    res = df[sizes >= 3][['id', 'visit_date', 'people']]
    return res.sort_values('id')

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 601. Human Traffic of Stadium?
LeetCode 601. Human Traffic of Stadium is rated Hard on LeetCode.
What topics does LeetCode 601. Human Traffic of Stadium cover?
LeetCode 601. Human Traffic of Stadium is tagged Database on LeetCode.

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