First and Last Call On the Same Day — LeetCode 1972 Python Solution

HardLeetCode PremiumDatabase
Problem
#1972
Reading time
8 min

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

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(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.

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