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.
1using System;
2using System.Collections.Generic;
3
4class Program {
5 public static List<Dictionary<string, object>> RearrangeProducts(List<Dictionary<string, object>> products) {
6 var result = new List<Dictionary<string, object>>();
7 var stores = new List<string> { "store1", "store2", "store3" };
8 foreach (var product in products) {
9 foreach (var store in stores) {
10 if (product[store] != null) {
11 result.Add(new Dictionary<string, object> {
12 { "product_id", product["product_id"] },
13 { "store", store },
14 { "price", product[store] }
15 });
16 }
17 }
18 }
19 return result;
20 }
21
22 static void Main() {
23 var products = new List<Dictionary<string, object>> {
24 new Dictionary<string, object> { { "product_id", 0 }, { "store1", 95 }, { "store2", 100 }, { "store3", 105 } },
25 new Dictionary<string, object> { { "product_id", 1 }, { "store1", 70 }, { "store2", null }, { "store3", 80 } }
26 };
27 var result = RearrangeProducts(products);
28 foreach (var row in result) {
29 Console.WriteLine($"{{product_id: {row["product_id"]}, store: {row["store"]}, price: {row["price"]}}}");
30 }
31 }
32}
This C# solution uses a similar approach with List of Dictionaries. It iterates through each product, checks each store, and appends a dictionary entry to the result list if the price is not null.
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.