Sponsored
Sponsored
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.
Time Complexity: O(N log N), due to sorting the records.
Space Complexity: O(N), for storing the latest prices of the products.
1from collections import defaultdict
2
3def product_prices_on_date(products):
4 # Default price before any change
5 base_price = 10
6 target_date = '2019-08-16'
7 product_latest = defaultdict(lambda: base_price)
8
9 for product_id, new_price, change_date in sorted(products, key=lambda x: (x[0], x[2])):
10 if change_date <= target_date:
11 product_latest[product_id] = new_price
12
13 return [[product_id, product_latest[product_id]] for product_id in product_latest]
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.
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.
Time Complexity: O(N log N), primarily due to map operations.
Space Complexity: O(N), to store product_id and price mappings.
1#include <iostream>
2#include <vector>
3#include <map>
4#include <tuple>
5#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;
}
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.