#1164
Product Price at a Given Date
MediumDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By using a single pass through the data and storing the latest price for each product in a dictionary, we can efficiently determine the price on the specified date without redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a dictionary to hold the latest price for each product.
- 2Step 2: Iterate through the Products table, updating the dictionary with the new price if the change_date is on or before the specified date.
- 3Step 3: For each product in the dictionary, if it has no price set, default to 10.
solution.py6 lines
1SELECT product_id, COALESCE(price, 10) AS price
2FROM (SELECT product_id, new_price AS price
3FROM Products
4WHERE change_date <= '2019-08-16'
5ORDER BY change_date DESC) AS latest_prices
6GROUP BY product_id;ℹ
Complexity note: The complexity is linear because we only need to traverse the list of products once, storing results in a dictionary.
- 1Understanding how to handle date comparisons is crucial.
- 2Using a dictionary can significantly reduce the number of operations needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.