HardNo. 1972LeetCode Premium
First and Last Call On the Same Day — LeetCode 1972 Python Solution
- Topics
- Database
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
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
+--------------+----------+
| 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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.