MediumNo. 1364LeetCode Premium

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

Topics
Database
Reading time
4 min

Table schema

SQLTable schema
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

SQLExample
+---------------+---------+
| 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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

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.

Free to download. Check it runs on your machine, then pick a plan.