Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using core interview patterns strategy.
Table: stores
+-------------+---------+ | Column Name | Type | +-------------+---------+ | store_id | int | | store_name | varchar | | location | varchar | +-------------+---------+ store_id is the unique identifier for this table. Each row contains information about a store and its location.
Table: inventory
+-------------+---------+ | Column Name | Type | +-------------+---------+ | inventory_id| int | | store_id | int | | product_name| varchar | | quantity | int | | price | decimal | +-------------+---------+ inventory_id is the unique identifier for this table. Each row represents the inventory of a specific product at a specific store.
Write a solution to find stores that have inventory imbalance - stores where the most expensive product has lower stock than the cheapest product.
3 different productsReturn the result table ordered by imbalance ratio in descending order, then by store name in ascending order.
The result format is in the following example.
Example:
Input:
stores table:
+----------+----------------+-------------+ | store_id | store_name | location | +----------+----------------+-------------+ | 1 | Downtown Tech | New York | | 2 | Suburb Mall | Chicago | | 3 | City Center | Los Angeles | | 4 | Corner Shop | Miami | | 5 | Plaza Store | Seattle | +----------+----------------+-------------+
inventory table:
+--------------+----------+--------------+----------+--------+ | inventory_id | store_id | product_name | quantity | price | +--------------+----------+--------------+----------+--------+ | 1 | 1 | Laptop | 5 | 999.99 | | 2 | 1 | Mouse | 50 | 19.99 | | 3 | 1 | Keyboard | 25 | 79.99 | | 4 | 1 | Monitor | 15 | 299.99 | | 5 | 2 | Phone | 3 | 699.99 | | 6 | 2 | Charger | 100 | 25.99 | | 7 | 2 | Case | 75 | 15.99 | | 8 | 2 | Headphones | 20 | 149.99 | | 9 | 3 | Tablet | 2 | 499.99 | | 10 | 3 | Stylus | 80 | 29.99 | | 11 | 3 | Cover | 60 | 39.99 | | 12 | 4 | Watch | 10 | 299.99 | | 13 | 4 | Band | 25 | 49.99 | | 14 | 5 | Camera | 8 | 599.99 | | 15 | 5 | Lens | 12 | 199.99 | +--------------+----------+--------------+----------+--------+
Output:
+----------+----------------+-------------+------------------+--------------------+------------------+ | store_id | store_name | location | most_exp_product | cheapest_product | imbalance_ratio | +----------+----------------+-------------+------------------+--------------------+------------------+ | 3 | City Center | Los Angeles | Tablet | Stylus | 40.00 | | 1 | Downtown Tech | New York | Laptop | Mouse | 10.00 | | 2 | Suburb Mall | Chicago | Phone | Case | 25.00 | +----------+----------------+-------------+------------------+--------------------+------------------+
Explanation:
The Results table is ordered by imbalance ratio in descending order, then by store name in ascending order
Problem summary: Table: stores +-------------+---------+ | Column Name | Type | +-------------+---------+ | store_id | int | | store_name | varchar | | location | varchar | +-------------+---------+ store_id is the unique identifier for this table. Each row contains information about a store and its location. Table: inventory +-------------+---------+ | Column Name | Type | +-------------+---------+ | inventory_id| int | | store_id | int | | product_name| varchar | | quantity | int | | price | decimal | +-------------+---------+ inventory_id is the unique identifier for this table. Each row represents the inventory of a specific product at a specific store. Write a solution to find stores that have inventory imbalance - stores where the most expensive product has lower stock than the cheapest product. For each store, identify the most expensive product (highest price) and its quantity For each store,
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
{"headers":{"stores":["store_id","store_name","location"],"inventory":["inventory_id","store_id","product_name","quantity","price"]},"rows":{"stores":[[1,"Downtown Tech","New York"],[2,"Suburb Mall","Chicago"],[3,"City Center","Los Angeles"],[4,"Corner Shop","Miami"],[5,"Plaza Store","Seattle"]],"inventory":[[1,1,"Laptop",5,999.99],[2,1,"Mouse",50,19.99],[3,1,"Keyboard",25,79.99],[4,1,"Monitor",15,299.99],[5,2,"Phone",3,699.99],[6,2,"Charger",100,25.99],[7,2,"Case",75,15.99],[8,2,"Headphones",20,149.99],[9,3,"Tablet",2,499.99],[10,3,"Stylus",80,29.99],[11,3,"Cover",60,39.99],[12,4,"Watch",10,299.99],[13,4,"Band",25,49.99],[14,5,"Camera",8,599.99],[15,5,"Lens",12,199.99]]}}Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// Auto-generated Java example from py.
class Solution {
public void exampleSolution() {
}
}
// Reference (py):
// # Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// import pandas as pd
//
//
// def find_inventory_imbalance(
// stores: pd.DataFrame, inventory: pd.DataFrame
// ) -> pd.DataFrame:
// # Step 1: Identify stores with at least 3 products
// store_counts = inventory["store_id"].value_counts()
// valid_stores = store_counts[store_counts >= 3].index
//
// # Step 2: Find most expensive product for each valid store
// # Sort by price (descending) then quantity (descending) and take first record per store
// most_expensive = (
// inventory[inventory["store_id"].isin(valid_stores)]
// .sort_values(["store_id", "price", "quantity"], ascending=[True, False, False])
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 3: Find cheapest product for each store
// # Sort by price (ascending) then quantity (descending) and take first record per store
// cheapest = (
// inventory.sort_values(
// ["store_id", "price", "quantity"], ascending=[True, True, False]
// )
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 4: Merge the two datasets on store_id
// merged = pd.merge(
// most_expensive, cheapest, on="store_id", suffixes=("_most", "_cheap")
// )
//
// # Step 5: Filter for cases where cheapest product has higher quantity than most expensive
// result = merged[merged["quantity_most"] < merged["quantity_cheap"]].copy()
//
// # Step 6: Calculate imbalance ratio (cheapest quantity / most expensive quantity)
// result["imbalance_ratio"] = (
// result["quantity_cheap"] / result["quantity_most"]
// ).round(2)
//
// # Step 7: Merge with store information to get store names and locations
// result = pd.merge(result, stores, on="store_id")
//
// # Step 8: Select and rename columns for final output
// result = result[
// [
// "store_id",
// "store_name",
// "location",
// "product_name_most",
// "product_name_cheap",
// "imbalance_ratio",
// ]
// ].rename(
// columns={
// "product_name_most": "most_exp_product",
// "product_name_cheap": "cheapest_product",
// }
// )
//
// # Step 9: Sort by imbalance ratio (descending) then store name (ascending)
// result = result.sort_values(
// ["imbalance_ratio", "store_name"], ascending=[False, True]
// ).reset_index(drop=True)
//
// return result
// Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// Auto-generated Go example from py.
func exampleSolution() {
}
// Reference (py):
// # Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// import pandas as pd
//
//
// def find_inventory_imbalance(
// stores: pd.DataFrame, inventory: pd.DataFrame
// ) -> pd.DataFrame:
// # Step 1: Identify stores with at least 3 products
// store_counts = inventory["store_id"].value_counts()
// valid_stores = store_counts[store_counts >= 3].index
//
// # Step 2: Find most expensive product for each valid store
// # Sort by price (descending) then quantity (descending) and take first record per store
// most_expensive = (
// inventory[inventory["store_id"].isin(valid_stores)]
// .sort_values(["store_id", "price", "quantity"], ascending=[True, False, False])
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 3: Find cheapest product for each store
// # Sort by price (ascending) then quantity (descending) and take first record per store
// cheapest = (
// inventory.sort_values(
// ["store_id", "price", "quantity"], ascending=[True, True, False]
// )
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 4: Merge the two datasets on store_id
// merged = pd.merge(
// most_expensive, cheapest, on="store_id", suffixes=("_most", "_cheap")
// )
//
// # Step 5: Filter for cases where cheapest product has higher quantity than most expensive
// result = merged[merged["quantity_most"] < merged["quantity_cheap"]].copy()
//
// # Step 6: Calculate imbalance ratio (cheapest quantity / most expensive quantity)
// result["imbalance_ratio"] = (
// result["quantity_cheap"] / result["quantity_most"]
// ).round(2)
//
// # Step 7: Merge with store information to get store names and locations
// result = pd.merge(result, stores, on="store_id")
//
// # Step 8: Select and rename columns for final output
// result = result[
// [
// "store_id",
// "store_name",
// "location",
// "product_name_most",
// "product_name_cheap",
// "imbalance_ratio",
// ]
// ].rename(
// columns={
// "product_name_most": "most_exp_product",
// "product_name_cheap": "cheapest_product",
// }
// )
//
// # Step 9: Sort by imbalance ratio (descending) then store name (ascending)
// result = result.sort_values(
// ["imbalance_ratio", "store_name"], ascending=[False, True]
// ).reset_index(drop=True)
//
// return result
# Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
import pandas as pd
def find_inventory_imbalance(
stores: pd.DataFrame, inventory: pd.DataFrame
) -> pd.DataFrame:
# Step 1: Identify stores with at least 3 products
store_counts = inventory["store_id"].value_counts()
valid_stores = store_counts[store_counts >= 3].index
# Step 2: Find most expensive product for each valid store
# Sort by price (descending) then quantity (descending) and take first record per store
most_expensive = (
inventory[inventory["store_id"].isin(valid_stores)]
.sort_values(["store_id", "price", "quantity"], ascending=[True, False, False])
.groupby("store_id")
.first()
.reset_index()
)
# Step 3: Find cheapest product for each store
# Sort by price (ascending) then quantity (descending) and take first record per store
cheapest = (
inventory.sort_values(
["store_id", "price", "quantity"], ascending=[True, True, False]
)
.groupby("store_id")
.first()
.reset_index()
)
# Step 4: Merge the two datasets on store_id
merged = pd.merge(
most_expensive, cheapest, on="store_id", suffixes=("_most", "_cheap")
)
# Step 5: Filter for cases where cheapest product has higher quantity than most expensive
result = merged[merged["quantity_most"] < merged["quantity_cheap"]].copy()
# Step 6: Calculate imbalance ratio (cheapest quantity / most expensive quantity)
result["imbalance_ratio"] = (
result["quantity_cheap"] / result["quantity_most"]
).round(2)
# Step 7: Merge with store information to get store names and locations
result = pd.merge(result, stores, on="store_id")
# Step 8: Select and rename columns for final output
result = result[
[
"store_id",
"store_name",
"location",
"product_name_most",
"product_name_cheap",
"imbalance_ratio",
]
].rename(
columns={
"product_name_most": "most_exp_product",
"product_name_cheap": "cheapest_product",
}
)
# Step 9: Sort by imbalance ratio (descending) then store name (ascending)
result = result.sort_values(
["imbalance_ratio", "store_name"], ascending=[False, True]
).reset_index(drop=True)
return result
// Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// Rust example auto-generated from py reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (py):
// # Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// import pandas as pd
//
//
// def find_inventory_imbalance(
// stores: pd.DataFrame, inventory: pd.DataFrame
// ) -> pd.DataFrame:
// # Step 1: Identify stores with at least 3 products
// store_counts = inventory["store_id"].value_counts()
// valid_stores = store_counts[store_counts >= 3].index
//
// # Step 2: Find most expensive product for each valid store
// # Sort by price (descending) then quantity (descending) and take first record per store
// most_expensive = (
// inventory[inventory["store_id"].isin(valid_stores)]
// .sort_values(["store_id", "price", "quantity"], ascending=[True, False, False])
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 3: Find cheapest product for each store
// # Sort by price (ascending) then quantity (descending) and take first record per store
// cheapest = (
// inventory.sort_values(
// ["store_id", "price", "quantity"], ascending=[True, True, False]
// )
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 4: Merge the two datasets on store_id
// merged = pd.merge(
// most_expensive, cheapest, on="store_id", suffixes=("_most", "_cheap")
// )
//
// # Step 5: Filter for cases where cheapest product has higher quantity than most expensive
// result = merged[merged["quantity_most"] < merged["quantity_cheap"]].copy()
//
// # Step 6: Calculate imbalance ratio (cheapest quantity / most expensive quantity)
// result["imbalance_ratio"] = (
// result["quantity_cheap"] / result["quantity_most"]
// ).round(2)
//
// # Step 7: Merge with store information to get store names and locations
// result = pd.merge(result, stores, on="store_id")
//
// # Step 8: Select and rename columns for final output
// result = result[
// [
// "store_id",
// "store_name",
// "location",
// "product_name_most",
// "product_name_cheap",
// "imbalance_ratio",
// ]
// ].rename(
// columns={
// "product_name_most": "most_exp_product",
// "product_name_cheap": "cheapest_product",
// }
// )
//
// # Step 9: Sort by imbalance ratio (descending) then store name (ascending)
// result = result.sort_values(
// ["imbalance_ratio", "store_name"], ascending=[False, True]
// ).reset_index(drop=True)
//
// return result
// Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// Auto-generated TypeScript example from py.
function exampleSolution(): void {
}
// Reference (py):
// # Accepted solution for LeetCode #3626: Find Stores with Inventory Imbalance
// import pandas as pd
//
//
// def find_inventory_imbalance(
// stores: pd.DataFrame, inventory: pd.DataFrame
// ) -> pd.DataFrame:
// # Step 1: Identify stores with at least 3 products
// store_counts = inventory["store_id"].value_counts()
// valid_stores = store_counts[store_counts >= 3].index
//
// # Step 2: Find most expensive product for each valid store
// # Sort by price (descending) then quantity (descending) and take first record per store
// most_expensive = (
// inventory[inventory["store_id"].isin(valid_stores)]
// .sort_values(["store_id", "price", "quantity"], ascending=[True, False, False])
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 3: Find cheapest product for each store
// # Sort by price (ascending) then quantity (descending) and take first record per store
// cheapest = (
// inventory.sort_values(
// ["store_id", "price", "quantity"], ascending=[True, True, False]
// )
// .groupby("store_id")
// .first()
// .reset_index()
// )
//
// # Step 4: Merge the two datasets on store_id
// merged = pd.merge(
// most_expensive, cheapest, on="store_id", suffixes=("_most", "_cheap")
// )
//
// # Step 5: Filter for cases where cheapest product has higher quantity than most expensive
// result = merged[merged["quantity_most"] < merged["quantity_cheap"]].copy()
//
// # Step 6: Calculate imbalance ratio (cheapest quantity / most expensive quantity)
// result["imbalance_ratio"] = (
// result["quantity_cheap"] / result["quantity_most"]
// ).round(2)
//
// # Step 7: Merge with store information to get store names and locations
// result = pd.merge(result, stores, on="store_id")
//
// # Step 8: Select and rename columns for final output
// result = result[
// [
// "store_id",
// "store_name",
// "location",
// "product_name_most",
// "product_name_cheap",
// "imbalance_ratio",
// ]
// ].rename(
// columns={
// "product_name_most": "most_exp_product",
// "product_name_cheap": "cheapest_product",
// }
// )
//
// # Step 9: Sort by imbalance ratio (descending) then store name (ascending)
// result = result.sort_values(
// ["imbalance_ratio", "store_name"], ascending=[False, True]
// ).reset_index(drop=True)
//
// return result
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.