Human Traffic of Stadium LeetCode Solution

Last updated on October 9th, 2024 at 06:25 pm

This Leetcode problem Human Traffic of Stadium LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Hard

Human Traffic of Stadium LeetCode Solution

Human Traffic of Stadium LeetCode Solution

Problem Statement

Column NameType
idint
visit_datedate
peopleint
Table: 

visit_date is the column with unique values for this table.
Each row of this table contains the visit date and visit id to the stadium with the number of people during the visit.
As the id increases, the date increases as well.

Write a solution to display the records with three or more rows with consecutive id‘s, and the number of people is greater than or equal to 100 for each.

Return the result table ordered by visit_date in ascending order.

The result format is in the following example.

Example 1:

idvisit_datepeople
12017-01-0110
22017-01-02109
32017-01-03150
42017-01-0499
52017-01-05145
62017-01-061455
72017-01-07199
82017-01-09188
Input:
id visit_datepeople
52017-01-05145
62017-01-061455
72017-01-07199
82017-01-09188
Output:

Explanation: The four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has >= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7. The rows with ids 2 and 3 are not included because we need at least three consecutive ids.

1. Human Traffic of Stadium LeetCode Solution MySQL

with q1 as (
  select 
    *, 
    count(*) over(
      order by 
        id range between current row 
        and 2 following
    ) following_cnt, 
    count(*) over(
      order by 
        id range between 2 preceding 
        and current row
    ) preceding_cnt, 
    count(*) over(
      order by 
        id range between 1 preceding 
        and 1 following
    ) current_cnt 
  from 
    stadium 
  where 
    people > 99
) 
select 
  id, 
  visit_date, 
  people 
from 
  q1 
where 
  following_cnt = 3 
  or preceding_cnt = 3 
  or current_cnt = 3 
order by 
  visit_date

2. Human Traffic of Stadium LeetCode Solution Pandas

import pandas as pd

def human_traffic(stadium: pd.DataFrame) -> pd.DataFrame:
    stadium = stadium.sort_values("id").query("people >= 100")
    stadium["row_nb"] = range(len(stadium))
    stadium["id_rownb_diff"] = stadium.id - stadium.row_nb
    stadium["size_of_consecutive_group"] = stadium.groupby("id_rownb_diff")["id"].transform("count")
    return stadium[stadium.size_of_consecutive_group >= 3][["id","visit_date","people"]]
Scroll to Top