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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 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# implementation mirrors the C++ approach in logic and behavior. It involves checking each product's date and updating prices in a dictionary accordingly. The list is then populated with the final values before being returned.