Number of Trusted Contacts of a Customer — LeetCode 1364 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1364
Reading time
4 min

Table schema

SQL
Table: Customers +---------------+---------+ | Column Name | Type | +---------------+---------+ | customer_id | int | | customer_name | varchar | | email | varchar | +---------------+---------+ customer_id is the column of unique values for this table. Each row of this table contains the name and the email of a customer of an online shop.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
| email         | varchar |
+---------------+---------+
customer_id is the column of unique values for this table.
Each row of this table contains the name and the email of a customer of an online shop.

Python solution

Python
import duckdb
import pandas as pd

def solution(customers: pd.DataFrame, contacts: pd.DataFrame, invoices: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Customers", customers)
    con.register("Contacts", contacts)
    con.register("Invoices", invoices)
    return con.execute("""SELECT
    invoice_id,
    t2.customer_name,
    price,
    COUNT(t3.user_id) AS contacts_cnt,
    COUNT(t4.email) AS trusted_contacts_cnt
FROM
    Invoices AS t1
    LEFT JOIN Customers AS t2 ON t1.user_id = t2.customer_id
    LEFT JOIN Contacts AS t3 ON t1.user_id = t3.user_id
    LEFT JOIN Customers AS t4 ON t3.contact_email = t4.email
GROUP BY invoice_id
ORDER BY invoice_id;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1364. Number of Trusted Contacts of a Customer?
LeetCode 1364. Number of Trusted Contacts of a Customer is rated Medium on LeetCode.
What topics does LeetCode 1364. Number of Trusted Contacts of a Customer cover?
LeetCode 1364. Number of Trusted Contacts of a Customer is tagged Database on LeetCode.
Is LeetCode 1364. Number of Trusted Contacts of a Customer a premium problem?
Yes. LeetCode 1364. Number of Trusted Contacts of a Customer 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