Product Sales Analysis III — LeetCode 1070 Python Solution

MediumDatabase
Problem
#1070
Reading time
4 min

Table schema

SQL
Table: Sales +-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +-------------+-------+ (sale_id, year) is the primary key (combination of columns with unique values) of this table. Each row records a sale of a product in a given year.

Example

SQL
+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id     | int   |
| product_id  | int   |
| year        | int   |
| quantity    | int   |
| price       | int   |
+-------------+-------+
(sale_id, year) is the primary key (combination of columns with unique values) of this table.
Each row records a sale of a product in a given year.
A product may have multiple sales entries in the same year.
Note that the per-unit price.

Python solution

Python
import duckdb
import pandas as pd

def solution(sales: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Sales", sales)
    return con.execute("""SELECT
    product_id,
    year AS first_year,
    quantity,
    price
FROM Sales
WHERE
    (product_id, year) IN (
        SELECT
            product_id,
            MIN(year) AS year
        FROM Sales
        GROUP BY product_id
    );""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1070. Product Sales Analysis III?
LeetCode 1070. Product Sales Analysis III is rated Medium on LeetCode.
What topics does LeetCode 1070. Product Sales Analysis III cover?
LeetCode 1070. Product Sales Analysis III is tagged Database on LeetCode.

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