EasyNo. 1677LeetCode Premium

Product's Worth Over Invoices — LeetCode 1677 Python Solution

Topics
Database
Reading time
3 min

Table schema

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

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

PythonSolution
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

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 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.

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