First and Last Call On the Same Day — LeetCode 1972 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #1972
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
SQL
Table: Calls +--------------+----------+ | Column Name | Type | +--------------+----------+ | caller_id | int | | recipient_id | int | | call_time | datetime | +--------------+----------+ (caller_id, recipient_id, call_time) is the primary key (combination of columns with unique values) for this table. Each row contains information about the time of a phone call between caller_id and recipient_id.Example
SQL
+--------------+----------+
| Column Name | Type |
+--------------+----------+
| caller_id | int |
| recipient_id | int |
| call_time | datetime |
+--------------+----------+
(caller_id, recipient_id, call_time) is the primary key (combination of columns with unique values) for this table.
Each row contains information about the time of a phone call between caller_id and recipient_id.Python solution
Python
import duckdb
import pandas as pd
def solution(calls: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Calls", calls)
return con.execute("""with s as (
select
*
from
Calls
union
all
select
recipient_id,
caller_id,
call_time
from
Calls
),
t as (
select
caller_id user_id,
FIRST_VALUE(recipient_id) over(
partition by DATE_FORMAT(call_time, '%Y-%m-%d'),
caller_id
order by
call_time asc
) first,
FIRST_VALUE(recipient_id) over(
partition by DATE_FORMAT(call_time, '%Y-%m-%d'),
caller_id
order by
call_time desc
) last
from
s
)
select
distinct user_id
from
t
where
first = last""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1972. First and Last Call On the Same Day?
- LeetCode 1972. First and Last Call On the Same Day is rated Hard on LeetCode.
- What topics does LeetCode 1972. First and Last Call On the Same Day cover?
- LeetCode 1972. First and Last Call On the Same Day is tagged Database on LeetCode.
- Is LeetCode 1972. First and Last Call On the Same Day a premium problem?
- Yes. LeetCode 1972. First and Last Call On the Same Day is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.