Problem 638

Abstract / Summary

Given item prices and special discount offers, find the lowest cost to buy a certain number of each item.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0638.py

class Solution:
    def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:
        size = len(price)

        # remove items which are for free
        for i in range(size):
            if price[i] == 0:
                needs[i] = 0

        # everything's for free
        needs = tuple(needs)
        if sum(needs) == 0:
            return 0

        # worst case: ignore all offers and pay full price
        limit = 0
        for p, n in zip(price, needs):
            limit += p * n

        # treat standard price as an offer of a single item
        for i in range(size):
            single    = [ 0 ] * size
            single[i] = 1
            special.append(single + [ price[i] ])

        # consider only offers which don't exceed the number of needed items
        offers = {}
        valid  = [ s for s in special if all( h <= n for h, n in zip(s, needs) ) ]
        for v in valid:
            items = tuple(v[ : -1])
            cost  = v[-1]
            if offers.get(items, +inf) > cost:
                offers[items] = cost

        todo = [ (0, needs) ]      # ( price paid so far, items still needed )
        seen = { needs: 0 }
        while True:
            cost, have = heappop(todo)

            # found lowest price
            if sum(have) == 0: # have == [ 0,0,0,... ]
                return cost

            # double-check that we haven't already processed it
            if seen[have] < cost:
                continue

            # try every offer
            for o in offers:
                total = cost + offers[o]
                if total > limit: # too expensive
                    continue

                next = [ h - oo for h, oo in zip(have, o) ]
                if min(next) >= 0: # must not buy more than needed
                    # ensure we haven't seen a better price
                    next = tuple(next)
                    if total < seen.get(next, +inf):
                        heappush(todo, ( total, next ))
                        seen[next] = total

                        # potential solution
                        if sum(next) == 0:
                            limit = total
64 lines | 2245 bytes | submitted May 21, 2024 | GitHub   32% comment ratio | tab size 4 | more than moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Bitmask
  • Dynamic Programming
  • Memoization
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The shoppingOffers method computes the minimum amount of money required to satisfy a shopping list (needs) given individual item prices (price) and a collection of bundle offers (special). It treats the problem as a shortest-path search in the space of remaining needs, where each offer corresponds to an edge whose weight is the offer’s cost. The algorithm explores this space with a priority queue, always expanding the state with the lowest accumulated cost, and stops when a state with no remaining items is reached.

Preprocessing of Free Items and Trivial Cases

The first loop scans the price list and forces any item whose unit price is zero to have a required quantity of zero. This eliminates unnecessary work for items that can be obtained without cost.

size = len(price)

# remove items which are for free
for i in range(size):
    if price[i] == 0:
        needs[i] = 0

After this adjustment the code converts needs to an immutable tuple and checks whether the total required quantity is already zero. If so, the function returns immediately with a cost of 0.

needs = tuple(needs)
if sum(needs) == 0:
    return 0

These steps handle the edge case where the shopping list is empty or all required items are free, avoiding any further computation.

Establishing an Upper Bound

The variable limit is initialized to the cost of buying every needed item at its regular price, i.e., the worst-case scenario where no special offers are used. This value serves as a dynamic upper bound that prunes any search paths that become more expensive than the best solution found so far.

limit = 0
for p, n in zip(price, needs):
    limit += p * n

Normalizing Prices as Single-Item Offers

To simplify the search, the algorithm treats buying a single unit of an item at its regular price as a special offer. It appends one such offer for each item to the special list.

for i in range(size):
    single    = [ 0 ] * size
    single[i] = 1
    special.append(single + [ price[i] ])

This transformation guarantees that every possible purchase can be expressed as a combination of offers, eliminating the need for separate handling of individual items during the search.

Filtering Valid Offers and Keeping the Cheapest Variant

Offers that require more items than are needed are discarded, because they can never be part of an optimal solution. The remaining offers are stored in a dictionary keyed by the tuple of item quantities, with the value being the lowest cost observed for that exact combination. If multiple offers provide the same quantities, only the cheapest one is retained.

offers = {}
valid  = [ s for s in special if all( h <= n for h, n in zip(s, needs) ) ]
for v in valid:
    items = tuple(v[ : -1])
    cost  = v[-1]
    if offers.get(items, +inf) > cost:
        offers[items] = cost

This step handles the edge case where duplicate offers exist with different prices, ensuring that the search never considers a sub-optimal duplicate.

Best-First Search with a Priority Queue

The core of the algorithm is a loop that repeatedly extracts the state with the smallest accumulated cost from a min-heap (todo). Each state consists of the current total cost and a tuple representing the remaining quantities (have). A dictionary seen records the cheapest cost at which each state has been reached, preventing redundant expansions.

todo = [ (0, needs) ]      # ( price paid so far, items still needed )
seen = { needs: 0 }
while True:
    cost, have = heappop(todo)

    # found lowest price
    if sum(have) == 0: # have == [ 0,0,0,... ]
        return cost

    # double-check that we haven't already processed it
    if seen[have] < cost:
        continue

    # try every offer
    for o in offers:
        total = cost + offers[o]
        if total > limit: # too expensive
            continue

        next = [ h - oo for h, oo in zip(have, o) ]
        if min(next) >= 0: # must not buy more than needed
            # ensure we haven't seen a better price
            next = tuple(next)
            if total < seen.get(next, +inf):
                heappush(todo, ( total, next ))
                seen[next] = total

                # potential solution
                if sum(next) == 0:
                    limit = total

When a state with zero remaining items is popped, its associated cost is the minimum possible, and the function returns it. The inner loop evaluates each stored offer, computes the new cost, and discards the transition if it exceeds the current limit. It also checks that applying the offer does not produce negative quantities, thereby respecting the constraint that the shopper cannot purchase more than needed. If a new state is reached at a lower cost than previously recorded, it is pushed onto the heap and the seen map is updated. When such a state represents completion, the limit is tightened to the newly discovered optimal cost, which further prunes subsequent expansions.

Edge Cases Handled

  • Items with a unit price of zero are automatically satisfied, preventing unnecessary branching.
  • An empty or fully satisfied needs list triggers an immediate return of zero.
  • Offers that request more items than the current need are filtered out before the search, ensuring they never cause negative inventory.
  • Duplicate offers with higher prices are collapsed to the cheapest variant, avoiding wasteful exploration of inferior paths.
  • The dynamic limit variable prevents the algorithm from pursuing paths that cannot improve upon the best solution already found.

Performance Optimizations

The algorithm incorporates several techniques that reduce the search space and improve runtime:

  • Early elimination of free items and trivial zero-need cases cuts off entire branches before any heap operations occur.
  • Converting the needs vector to a tuple enables fast hashing and dictionary lookups, making the seen map efficient.
  • Storing only the cheapest cost for each distinct offer combination avoids redundant work when multiple offers share the same item quantities.
  • The priority queue ensures that states are expanded in order of increasing total cost, guaranteeing that the first complete state encountered is optimal.
  • The limit variable acts as a global upper bound that is tightened whenever a complete solution is discovered, allowing the loop to skip any transition whose cumulative cost already exceeds this bound.
  • By appending unit-price offers to the list of specials, the algorithm unifies the handling of regular purchases and bundles, eliminating the need for separate logic and reducing branching.

Together, these strategies enable the method to solve the combinatorial pricing problem efficiently, even when the number of items and offers grows moderately large.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a very big store where you have a shopping list for groceries like apples, bananas, and cherries. Every fruit has a normal price, but the store also has special bundles where you can grab a few things together for a cheaper price. The goal is to get exactly what is on your list while spending as little money as possible.

First, the code checks if anything on your list is already free. If it is, those items get crossed off the list because you do not have to pay for them.

Next, it looks at the normal price for every item. It imagines a scenario where you ignore all the special bundles and just pay the regular price for everything. This sets a budget limit so you know the most expensive amount you could possibly pay.

Then, the code treats the price of each single fruit as if it were a tiny bundle. This makes it easier to look at everything as if it were just a group of choices. It throws away any bundles that offer more than what you need, because you only want the specific amounts on your list.

Now, the code starts a game of exploring paths. It keeps track of how much money you have spent so far and what items you still need to find. It uses a special tool called a priority queue to always look at the cheapest way to shop first.

It keeps trying different bundles to see if it can reach the goal of having all your items while keeping the total cost low. Every time it finds a way to get certain items for a better price than it had discovered before, it remembers that path. If it ever finds a way to finish the shopping list without going over the budget limit, it keeps that price in mind.

By testing all these different bundles over and over, the code eventually clears your list and finds the smallest amount of money needed to buy everything.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.31 | σ = 2.05

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
wisdompeak C++
34 links | 20 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Fun Facts

Longest ELI5 with 1780 characters.

1 fun fact

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality