HardNo. 2362LeetCode Premium

Generate the Invoice — LeetCode 2362 Python Solution

Topics
Database
Reading time
5 min

Table schema

SQLTable schema
Table: Products +-------------+------+ | Column Name | Type | +-------------+------+ | product_id | int | | price | int | +-------------+------+ product_id contains unique values. Each row in this table shows the ID of a product and the price of one unit.

Example

SQLExample
+-------------+------+
| Column Name | Type |
+-------------+------+
| product_id  | int  |
| price       | int  |
+-------------+------+
product_id contains unique values.
Each row in this table shows the ID of a product and the price of one unit.

Python solution

PythonSolution
import duckdb
import pandas as pd

def solution(products: pd.DataFrame, purchases: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Products", products)
    con.register("Purchases", purchases)
    return con.execute("""WITH
    P AS (
        SELECT *
        FROM
            Purchases
            JOIN Products USING (product_id)
    ),
    T AS (
        SELECT invoice_id, SUM(price * quantity) AS amount
        FROM P
        GROUP BY invoice_id
        ORDER BY 2 DESC, 1
        LIMIT 1
    )
SELECT product_id, quantity, (quantity * price) AS price
FROM
    P
    JOIN T USING (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 2362. Generate the Invoice?

LeetCode 2362. Generate the Invoice is rated Hard on LeetCode.

What topics does LeetCode 2362. Generate the Invoice cover?

LeetCode 2362. Generate the Invoice is tagged Database on LeetCode.

Is LeetCode 2362. Generate the Invoice a premium problem?

Yes. LeetCode 2362. Generate the Invoice 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.