Sponsored
Sponsored
This approach involves iterating over each row of the original table and for each product, iterating over the store columns. For each store, if the price is not null, a new entry with the product_id, store name, and price is added to the result.
Time Complexity: O(n * m), where n is the number of products and m is the number of stores. Space Complexity: O(n * m), as we store results for each product-store where a price exists.
1def rearrange_products(products):
2 result = []
3 stores = ['store1', 'store2', 'store3']
4 for product in products:
5 product_id = product['product_id']
6 for store in stores:
7 if product[store] is not None:
8 result.append({'product_id': product_id, 'store': store, 'price': product[store]})
9 return result
10
11# Example usage
12products = [{'product_id': 0, 'store1': 95, 'store2': 100, 'store3': 105}, {'product_id': 1, 'store1': 70, 'store2': None, 'store3': 80}]
13print(rearrange_products(products))
This solution defines a function rearrange_products that takes a list of dictionaries as input, representing rows from the Products table. It iterates through each product and nested within that loop, iterates over the stores to check if the price is available. If so, the function appends a dictionary with the product_id, store, and price to the result list.
Using language constructs similar to SQL's UNPIVOT operation, we will extract non-null values for each store and create a new list with structure (product_id, store, price).
Time Complexity: O(n * m), Space Complexity: O(n * m).
1function rearrangeProducts(products) {
2 let result =
This JavaScript solution leverages functions like forEach to iterate over products and stores, adding new objects to result when a store has a non-null price.