#3626

Find Stores with Inventory Imbalance

Medium
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a single pass to gather the most and least expensive products for each store, then compare their quantities. This is efficient and leverages data structures for quick lookups.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a dictionary to store the most and least expensive products for each store.
  2. 2Step 2: Iterate through the inventory to populate the dictionary with max and min prices and their quantities.
  3. 3Step 3: Filter stores where the quantity of the most expensive product is less than that of the cheapest.
solution.py1 lines
1SELECT store_id FROM (SELECT store_id, MAX(price) AS max_price, MIN(price) AS min_price FROM inventory GROUP BY store_id) AS prices JOIN inventory ON prices.store_id = inventory.store_id WHERE inventory.price = prices.max_price AND inventory.quantity < (SELECT quantity FROM inventory WHERE store_id = prices.store_id AND price = prices.min_price);

Complexity note: Single pass through inventory for max/min and another for filtering, leading to linear time complexity.

  • 1Identifying extremes (max/min) is key to solving imbalance problems.
  • 2Using efficient data structures can significantly reduce complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.