KatInterview

638. Shopping Offers

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum cost to purchase a specific set of items, given their individual prices and a list of special offers (bundles). A key constraint is that we cannot buy more of any item than we need. This problem can be modeled as finding the shortest path in a state-space graph, where each state represents the remaining items we need to buy.

Solution

Shopping Offers in Python

class Solution:
    def shoppingOffers(self, price: list[int], special: list[list[int]], needs: list[int]) -> int:
        # Memoization dictionary to store results for subproblems.
        memo = {}
        n = len(price)

        def dfs(current_needs):
            # Use a tuple as a key for the memoization dictionary as lists are not hashable.
            needs_tuple = tuple(current_needs)
            if needs_tuple in memo:
                return memo[needs_tuple]

            # Option 1: Buy all items individually.
            # This serves as the initial minimum cost (upper bound).
            min_cost = sum(current_needs[i] * price[i] for i in range(n))

            # Option 2: Try to use each special offer.
            for offer in special:
                next_needs = list(current_needs)
                can_use_offer = True
                
                # Check if the current offer is applicable.
                for i in range(n):
                    if next_needs[i] < offer[i]:
                        can_use_offer = False
                        break
                    next_needs[i] -= offer[i]

                # If the offer can be used, recursively find the minimum cost.
                if can_use_offer:
                    # The last element of the offer is its price.
                    offer_price = offer[-1]
                    min_cost = min(min_cost, offer_price + dfs(next_needs))
            
            # Store the computed minimum cost and return it.
            memo[needs_tuple] = min_cost
            return min_cost

        return dfs(needs)

Shopping Offers in Java

class Solution {
    // Memoization table to store results for subproblems (needs -> min_cost).
    private Map<List<Integer>, Integer> memo = new HashMap<>();

    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        return dfs(price, special, needs);
    }

    private int dfs(List<Integer> price, List<List<Integer>> special, List<Integer> currentNeeds) {
        // If we have already computed the result for this state, return it.
        if (memo.containsKey(currentNeeds)) {
            return memo.get(currentNeeds);
        }

        int n = price.size();

        // Option 1: Buy all items individually.
        // This serves as the initial minimum cost (upper bound).
        int minCost = 0;
        for (int i = 0; i < n; i++) {
            minCost += currentNeeds.get(i) * price.get(i);
        }

        // Option 2: Try to use each special offer.
        for (List<Integer> offer : special) {
            List<Integer> nextNeeds = new ArrayList<>(currentNeeds);
            boolean canUseOffer = true;

            // Check if the current offer is applicable.
            for (int i = 0; i < n; i++) {
                if (nextNeeds.get(i) < offer.get(i)) {
                    canUseOffer = false;
                    break;
                }
                nextNeeds.set(i, nextNeeds.get(i) - offer.get(i));
            }

            // If the offer can be used, recursively find the minimum cost for the remaining needs.
            if (canUseOffer) {
                minCost = Math.min(minCost, offer.get(n) + dfs(price, special, nextNeeds));
            }
        }

        // Store the computed minimum cost in the memoization table and return it.
        memo.put(currentNeeds, minCost);
        return minCost;
    }
}

Shopping Offers in C++

class Solution {
public:
    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
        // Memoization table to store results for subproblems.
        // The key is the vector of current needs.
        map<vector<int>, int> memo;
        return solve(price, special, needs, memo);
    }

private:
    int solve(const vector<int>& price, const vector<vector<int>>& special, vector<int> current_needs, map<vector<int>, int>& memo) {
        // If we have already computed the result for this state, return it.
        if (memo.count(current_needs)) {
            return memo[current_needs];
        }

        int n = price.size();
        
        // Option 1: Buy all items individually.
        // This serves as the initial minimum cost (upper bound).
        int min_cost = 0;
        for (int i = 0; i < n; ++i) {
            min_cost += current_needs[i] * price[i];
        }

        // Option 2: Try to use each special offer.
        for (const auto& offer : special) {
            vector<int> next_needs = current_needs;
            bool can_use_offer = true;

            // Check if the current offer is applicable.
            for (int i = 0; i < n; ++i) {
                if (next_needs[i] < offer[i]) {
                    can_use_offer = false;
                    break;
                }
                next_needs[i] -= offer[i];
            }

            // If the offer can be used, recursively find the minimum cost for the remaining needs.
            if (can_use_offer) {
                min_cost = min(min_cost, offer[n] + solve(price, special, next_needs, memo));
            }
        }
        
        // Store the computed minimum cost in the memoization table and return it.
        return memo[current_needs] = min_cost;
    }
};

Shopping Offers in TypeScript

function shoppingOffers(price: number[], special: number[][], needs: number[]): number {
    // Memoization map to store results for subproblems (needs_string -> min_cost).
    const memo = new Map<string, number>();
    const n = price.length;

    function dfs(currentNeeds: number[]): number {
        // Use a string representation of the array as the key for the map.
        const key = currentNeeds.join(',');
        if (memo.has(key)) {
            return memo.get(key)!;
        }

        // Option 1: Buy all items individually.
        // This serves as the initial minimum cost (upper bound).
        let minCost = 0;
        for (let i = 0; i < n; i++) {
            minCost += currentNeeds[i] * price[i];
        }

        // Option 2: Try to use each special offer.
        for (const offer of special) {
            const nextNeeds = [...currentNeeds]; // Create a copy of current needs
            let canUseOffer = true;

            // Check if the current offer is applicable.
            for (let i = 0; i < n; i++) {
                if (nextNeeds[i] < offer[i]) {
                    canUseOffer = false;
                    break;
                }
                nextNeeds[i] -= offer[i];
            }

            // If the offer can be used, recursively find the minimum cost.
            if (canUseOffer) {
                const offerPrice = offer[n];
                minCost = Math.min(minCost, offerPrice + dfs(nextNeeds));
            }
        }

        // Store the computed minimum cost in the memoization map and return it.
        memo.set(key, minCost);
        return minCost;
    }

    return dfs(needs);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.