Number of Calls Between Two Persons — LeetCode 1699 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1699
Reading time
3 min

Table schema

SQL
Table: Calls +-------------+---------+ | Column Name | Type | +-------------+---------+ | from_id | int | | to_id | int | | duration | int | +-------------+---------+ This table does not have a primary key (column with unique values), it may contain duplicates. This table contains the duration of a phone call between from_id and to_id.

Example

SQL
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| from_id     | int     |
| to_id       | int     |
| duration    | int     |
+-------------+---------+
This table does not have a primary key (column with unique values), it may contain duplicates.
This table contains the duration of a phone call between from_id and to_id.
from_id != to_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("""SELECT
    IF(from_id < to_id, from_id, to_id) AS person1,
    IF(from_id < to_id, to_id, from_id) AS person2,
    COUNT(1) AS call_count,
    SUM(duration) AS total_duration
FROM Calls
GROUP BY 1, 2;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1699. Number of Calls Between Two Persons?
LeetCode 1699. Number of Calls Between Two Persons is rated Medium on LeetCode.
What topics does LeetCode 1699. Number of Calls Between Two Persons cover?
LeetCode 1699. Number of Calls Between Two Persons is tagged Database on LeetCode.
Is LeetCode 1699. Number of Calls Between Two Persons a premium problem?
Yes. LeetCode 1699. Number of Calls Between Two Persons 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