Similar Problems

Similar Problems not available

Products Price For Each Store - Leetcode Solution

Companies:

LeetCode:  Products Price For Each Store Leetcode Solution

Difficulty: Easy

Topics: database  

Problem Statement:

Given an array of n products and the price of each product in different stores, you need to create an array of n elements, where each element represents the minimum price that product is available for across all the stores.

Input: The input contains two integer arrays where the first array 'products' represents the products and the second array 'prices' represents the price of each product in different stores.

Output: The output is an array of n elements where each element represents the minimum price that product is available for across all the stores.

Example:

Input: Products = [1, 2, 3, 4, 5] Prices = [[10, 15, 12], [15, 30, 25], [20, 25, 30], [10, 20, 40], [30, 35, 50]]

Output: [10, 15, 12, 10, 30]

Explanation: For product 1, minimum price is 10. For product 2, minimum price is 15. For product 3, minimum price is 12. For product 4, minimum price is 10. For product 5, minimum price is 30.

Solution:

To solve this problem, we need to find the minimum price of each product i.e. the smallest value in the corresponding column of the given 2-D array. We can do this by iterating through each column of the array (each store) and finding the minimum value in it. Once we have the minimum value for each column, we can populate our output array with those values. Here is the Python code for the same:

def get_min_prices_for_products(products, prices): n = len(products) result = [] for i in range(n): min_price = prices[i][0] for j in range(1, len(prices[i])): if prices[i][j] < min_price: min_price = prices[i][j] result.append(min_price) return result

Testing the function with the given example

products = [1, 2, 3, 4, 5] prices = [[10, 15, 12], [15, 30, 25], [20, 25, 30], [10, 20, 40], [30, 35, 50]] result = get_min_prices_for_products(products, prices) print(result)

Output: [10, 15, 12, 10, 30]

Time Complexity: The time complexity of the above solution is O(n*m), where n is the number of products and m is the number of stores. We are iterating through each store for each product to find the minimum price.

Space Complexity: The space complexity of the above solution is O(n), where n is the number of products. We are using a single array to store the minimum price for each product.

Products Price For Each Store Solution Code

1