Product Price at a Given Date — LeetCode 1164 Python Solution
MediumDatabase
- Problem
- #1164
- Reading time
- 4 min
- Source
- leetcode.com
Table schema
SQL
Table: Products +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | new_price | int | | change_date | date | +---------------+---------+ (product_id, change_date) is the primary key (combination of columns with unique values) of this table. Each row of this table indicates that the price of some product was changed to a new price at some date.Example
SQL
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| new_price | int |
| change_date | date |
+---------------+---------+
(product_id, change_date) is the primary key (combination of columns with unique values) of this table.
Each row of this table indicates that the price of some product was changed to a new price at some date.Python solution
Python
import duckdb
import pandas as pd
def solution(products: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Products", products)
return con.execute("""WITH
T AS (SELECT DISTINCT product_id FROM Products),
P AS (
SELECT product_id, new_price AS price
FROM Products
WHERE
(product_id, change_date) IN (
SELECT product_id, MAX(change_date) AS change_date
FROM Products
WHERE change_date <= '2019-08-16'
GROUP BY 1
)
)
SELECT product_id, IFNULL(price, 10) AS price
FROM
T
LEFT JOIN P USING (product_id);""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1164. Product Price at a Given Date?
- LeetCode 1164. Product Price at a Given Date is rated Medium on LeetCode.
- What topics does LeetCode 1164. Product Price at a Given Date cover?
- LeetCode 1164. Product Price at a Given Date is tagged Database on LeetCode.