Generate the Invoice — LeetCode 2362 Python Solution

HardLeetCode PremiumDatabase
Problem
#2362
Reading time
5 min

Table schema

SQL
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

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

Python
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

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

Related problems

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.

Get Stealth Interview