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.
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.