Merge Overlapping Events in the Same Hall — LeetCode 2494 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #2494
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
SQL
Table: HallEvents +-------------+------+ | Column Name | Type | +-------------+------+ | hall_id | int | | start_day | date | | end_day | date | +-------------+------+ This table may contain duplicates rows. Each row of this table indicates the start day and end day of an event and the hall in which the event is held.Example
SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| hall_id | int |
| start_day | date |
| end_day | date |
+-------------+------+
This table may contain duplicates rows.
Each row of this table indicates the start day and end day of an event and the hall in which the event is held.Python solution
Python
import duckdb
import pandas as pd
def solution(hall_events: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("HallEvents", hall_events)
return con.execute("""WITH
S AS (
SELECT
hall_id,
start_day,
end_day,
MAX(end_day) OVER (
PARTITION BY hall_id
ORDER BY start_day
) AS cur_max_end_day
FROM HallEvents
),
T AS (
SELECT
*,
IF(
start_day <= LAG(cur_max_end_day) OVER (
PARTITION BY hall_id
ORDER BY start_day
),
0,
1
) AS start
FROM S
),
P AS (
SELECT
*,
SUM(start) OVER (
PARTITION BY hall_id
ORDER BY start_day
) AS gid
FROM T
)
SELECT hall_id, MIN(start_day) AS start_day, MAX(end_day) AS end_day
FROM P
GROUP BY hall_id, gid;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 2494. Merge Overlapping Events in the Same Hall?
- LeetCode 2494. Merge Overlapping Events in the Same Hall is rated Hard on LeetCode.
- What topics does LeetCode 2494. Merge Overlapping Events in the Same Hall cover?
- LeetCode 2494. Merge Overlapping Events in the Same Hall is tagged Database on LeetCode.
- Is LeetCode 2494. Merge Overlapping Events in the Same Hall a premium problem?
- Yes. LeetCode 2494. Merge Overlapping Events in the Same Hall is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.