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.
1function productPricesOnDate(products) {
2 const basePrice = 10;
3 const targetDate = '2019-08-16';
4 const productLatest = {};
5
6 products.sort((a, b) => {
7 if (a[0] === b[0]) {
8 return new Date(a[2]) - new Date(b[2]);
9 }
10 return a[0] - b[0];
11 });
12
13 for (const [product_id, new_price, change_date] of products) {
14 if (change_date <= targetDate) {
15 productLatest[product_id] = new_price;
16 }
17 }
18
19 return Object.entries(productLatest).map(([product_id, price]) => ({
20 product_id: parseInt(product_id, 10),
21 price: price || basePrice,
22 }));
23}
This JavaScript function follows the same logic as the Python solution. We sort the products first and update a dictionary with the latest price for each product on or before the target date, using a base price if no such price is found. We then map through this dictionary to structure the result.
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.