Product Price at a Given Date solution and explanation
9 more videos on this problem
Product Price at a Given Date | Leetcode 1164 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 11:46 · 15K views
LeetCode Medium 1164 Amazon Interview SQL Question with Detailed ExplanationEveryday Data Science · 9:50 · 10K views
34. Product Price at a Given Date | SQL Interview Questions and AnswersStart Practicing · 8:37 · 8K views
LeetCode 1164: Product Price at a Given Date [SQL]Frederik Müller · 14:32 · 3K views
LeetCode - 1164. Product Price at a Given Date (SQL)Chain Of Thought · 9:07 · 525 views
1164 Product Price at a Given Date| Day 68 Of 100 Days Of SQL Challenge | LeetCodeEduZy · 12:59 · 211 views
1164. Product Price at a Given Date | SQL Leetcode | Top 50 sql Question #sql #leetcodeSheCodes · 7:23 · 161 views
product price at a given date (1164) MS SQL Server programming interview questions on Leetcode.comWeb Reviews · 18:00 · 153 views
Leetcode SQL 50 | 1164. Product Price at a Given Date SolutionTrang Ng · 14:23 · 146 views
#SQL Leetcode SQL 50 #34: 1164: Product Price at a Given Date.The Code Samples · 10:52 · 144 views
The problem
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.
Write a solution to find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input: Products table: +------------+-----------+-------------+ | product_id | new_price | change_date | +------------+-----------+-------------+ | 1 | 20 | 2019-08-14 | | 2 | 50 | 2019-08-14 | | 1 | 30 | 2019-08-15 | | 1 | 35 | 2019-08-16 | | 2 | 65 | 2019-08-17 | | 3 | 20 | 2019-08-18 | +------------+-----------+-------------+ Output: +------------+-------+ | product_id | price | +------------+-------+ | 2 | 50 | | 1 | 35 | | 3 | 10 | +------------+-------+
Approach overview
Problem Overview: You are given a table of product price changes where each record stores product_id, new_price, and the change_date. The task is to return the price of every product on a specific date. If a product has no recorded price change before that date, its price defaults to 10. The challenge is determining the most recent price update that occurred on or before the given date for each product.
Approach 1: Sort and Group by Product ID and Change Date (O(n log n) time, O(n) space)
This approach processes the data similarly to how you would handle event timelines. First, sort all records by product_id and change_date. Then iterate through the sorted list while grouping entries by product. For each product, keep updating the current price whenever the change_date is less than or equal to the target date. The last valid update becomes the product's price. If no valid update exists, return the default price of 10. Sorting ensures chronological processing, while grouping makes it easy to track the latest valid change for each product.
This technique is straightforward in languages like Python or JavaScript using sorting plus dictionary/group structures. It works well when records must be processed in memory and mirrors patterns used in sorting and timeline-style data problems.
Approach 2: Use SQL-like Logic to Handle Dates (O(n) time, O(n) space)
A more database-oriented solution directly models the problem as a query. For each product, you want the row with the maximum change_date that is still less than or equal to the target date. This can be implemented using filtering plus aggregation logic similar to SQL's MAX(change_date) with grouping. First filter records where change_date <= target_date, then determine the latest change per product. Join or map that result back to retrieve the corresponding price. If a product has no qualifying record, assign the default value.
This mirrors patterns used in database and SQL queries where you compute the latest event before a timestamp. In languages like C++ or C#, you can replicate this with hash maps that track the best date seen per product while iterating through the dataset.
Recommended for interviews: The SQL-style aggregation approach is typically preferred. It directly models the requirement: "latest price change before a given date." Interviewers expect candidates to recognize the max-date-per-group pattern and implement it efficiently. The sorting and grouping approach still demonstrates solid reasoning and works well when the dataset is processed sequentially.
Approach 1: Approach 1: Sort and Group by Product ID and Change Date
In this approach, we can utilize sorting and grouping to find the last change before or on the specified date. We'll sort the input by product_id and change_date thus facilitating checking the last change on or before 2019-08-16. If no change is present by that date, we assign a default price of 10 for those products.
from collections import defaultdict
def product_prices_on_date(products):
# Default price before any change
base_price = 10
target_date = '2019-08-16'
product_latest = defaultdict(lambda: base_price)
for product_id, new_price, change_date in sorted(products, key=lambda x: (x[0], x[2])):
if change_date <= target_date:
product_latest[product_id] = new_price
return [[product_id, product_latest[product_id]] for product_id in product_latest]function productPricesOnDate(products) {
const basePrice = 10;
const targetDate = '2019-08-16';
const productLatest = {};
products.sort((a, b) => {
if (a[0] === b[0]) {
return new Date(a[2]) - new Date(b[2]);
}
return a[0] - b[0];
});
for (const [product_id, new_price, change_date] of products) {
if (change_date <= targetDate) {
productLatest[product_id] = new_price;
}
}
return Object.entries(productLatest).map(([product_id, price]) => ({
product_id: parseInt(product_id, 10),
price: price || basePrice,
}));
}This solution uses a default dictionary initialized with base price 10. We iterate through the sorted list of products by product_id and date. For each product, if the change date is on or before the target date, we update the product's price in the dictionary. Finally, we prepare a list of results showing the product_id and its corresponding price on the given date.
Time Complexity: O(N log N), due to sorting the records.
Space Complexity: O(N), for storing the latest prices of the products.
Approach 2: Approach 2: Use SQL-like Logic to Handle Dates
This approach simulates SQL operations in code logic to find the latest price for a given product_id on or before 2019-08-16. This can be done by first grouping by product_id and filtering with a date condition.
#include <iostream>
#include <vector>
#include <map>
#include <tuple>
#include <string>
#include <algorithm>
using namespace std;
vector<pair<int, int>> productPricesOnDate(vector<tuple<int, int, string>> &products) {
int basePrice = 10;
string targetDate = "2019-08-16";
map<int, int> productLatestPrice;
for (const auto &[product_id, new_price, change_date] : products) {
if (change_date <= targetDate) {
productLatestPrice[product_id] = max(productLatestPrice[product_id], new_price);
}
}
vector<pair<int, int>> result;
for (const auto &[product_id, price]: productLatestPrice) {
result.emplace_back(product_id, (price != 0) ? price : basePrice);
}
return result;
}using System;
using System.Collections.Generic;
public class Solution {
public List<(int, int)> ProductPricesOnDate(List<(int, int, DateTime)> products) {
int basePrice = 10;
DateTime targetDate = new DateTime(2019, 8, 16);
var productLatestPrice = new Dictionary<int, int>();
foreach (var (product_id, new_price, change_date) in products) {
if (change_date <= targetDate) {
if (!productLatestPrice.ContainsKey(product_id) || productLatestPrice[product_id] < new_price) {
productLatestPrice[product_id] = new_price;
}
}
}
var result = new List<(int, int)>();
foreach (var kvp in productLatestPrice) {
result.Add((kvp.Key, kvp.Value != 0 ? kvp.Value : basePrice));
}
return result;
}
}This C++ code uses STL map to mimic SQL grouping and filtering. It iterates over each record, checking change dates and storing the maximum price for each product that is valid for the date. The final step is to collect results by comparing stored prices against the base price.
Time Complexity: O(N log N), primarily due to map operations.
Space Complexity: O(N), to store product_id and price mappings.
Approach 3: Subquery + Join
We can use a subquery to find the price of the last price change for each product before the given date, and record it in the P table. Then, we can find all product_ids in the T table. Finally, we can left join the T table with the P table on product_id to get the final result.
# Write your MySQL query statement below
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);Approach 4: Default Approach
# Write your MySQL query statement below
WITH
P AS (
SELECT p1.product_id, new_price, change_date
FROM
(
SELECT DISTINCT product_id
FROM Products
) AS p1
LEFT JOIN Products AS p2
ON p1.product_id = p2.product_id AND p2.change_date <= '2019-08-16'
),
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY product_id
ORDER BY change_date DESC
) AS rk
FROM P
)
SELECT product_id, IFNULL(new_price, 10) AS price
FROM T
WHERE rk = 1;Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Sort and Group by Product ID and Change Date | Time Complexity: O(N log N), due to sorting the records. |
| Approach 2: Use SQL-like Logic to Handle Dates | Time Complexity: O(N log N), primarily due to map operations. |
| Subquery + Join | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sort and Group by Product ID and Change Date | O(n log n) | O(n) | When processing records sequentially in application code or when sorting simplifies timeline tracking. |
| SQL-like Date Filtering with Latest Change | O(n) | O(n) | Best for database-style problems where you need the latest record before a timestamp for each group. |
Frequently asked questions
Is Product Price at a Given Date easy or hard?
Product Price at a Given Date is classified as a Medium difficulty problem. The main challenge is recognizing the pattern of selecting the most recent record before a given timestamp for each group, which is common in database and SQL interview questions.
Product Price at a Given Date Python/Java solution
Python implementations typically sort records or use dictionaries to track the latest valid change date per product. Java solutions often use HashMap structures or database-style grouping logic. Both approaches achieve O(n) or O(n log n) complexity depending on whether sorting is required.
How to solve Product Price at a Given Date in O(n)?
Iterate through the records while keeping a hash map that stores the latest valid change_date for each product where change_date <= target_date. Update the stored price whenever a later valid date is found. After processing all records, return the tracked price for each product or the default value 10 if no update exists.
What is the best approach for Product Price at a Given Date?
The most effective approach uses SQL-style logic: filter rows where change_date is less than or equal to the target date, then select the maximum change_date per product. This directly identifies the most recent price update before the given date. The method runs in O(n) time with O(n) space using hash maps or database grouping.
Is Product Price at a Given Date asked at Google/Amazon/Meta?
Database and SQL-style query problems like this frequently appear in interviews at companies such as Amazon, Google, and Meta. They test understanding of grouping, filtering by date, and retrieving the most recent record per entity.
What data structure is used in Product Price at a Given Date?
Common solutions use hash maps or dictionaries to store the latest price change per product while iterating through records. Sorting structures or SQL GROUP BY logic may also be used to organize updates by product and date.
What is the time complexity of Product Price at a Given Date?
The optimal approach runs in O(n) time by scanning all price change records once and tracking the latest valid change for each product. A sorting-based approach requires O(n log n) time due to ordering by product_id and change_date.
