Product's Worth Over Invoices — LeetCode 1677 Python Solution

EasyLeetCode PremiumDatabase
Problem
#1677
Reading time
3 min

Table schema

SQL
Table: Product +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | name | varchar | +-------------+---------+ product_id is the column with unique values for this table. This table contains the ID and the name of the product.

Example

SQL
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| name        | varchar |
+-------------+---------+
product_id is the column with unique values for this table.
This table contains the ID and the name of the product. The name consists of only lowercase English letters. No two products have the same name.

Python solution

Python
import duckdb
import pandas as pd

def solution(product: pd.DataFrame, invoice: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Product", product)
    con.register("Invoice", invoice)
    return con.execute("""SELECT
    name,
    IFNULL(SUM(rest), 0) AS rest,
    IFNULL(SUM(paid), 0) AS paid,
    IFNULL(SUM(canceled), 0) AS canceled,
    IFNULL(SUM(refunded), 0) AS refunded
FROM
    Product
    LEFT JOIN Invoice USING (product_id)
GROUP BY product_id
ORDER BY name;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1677. Product's Worth Over Invoices?
LeetCode 1677. Product's Worth Over Invoices is rated Easy on LeetCode.
What topics does LeetCode 1677. Product's Worth Over Invoices cover?
LeetCode 1677. Product's Worth Over Invoices is tagged Database on LeetCode.
Is LeetCode 1677. Product's Worth Over Invoices a premium problem?
Yes. LeetCode 1677. Product's Worth Over Invoices 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