Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #638: Shopping Offers

In this guide, we solve Leetcode #638 Shopping Offers in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

In LeetCode Store, there are n items to sell. Each item has a price.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Bit Manipulation, Memoization, Array, Dynamic Programming, Backtracking, Bitmask

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2] Output: 14 Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. In special offer 1, you can pay $5 for 3A and 0B In special offer 2, you can pay $10 for 1A and 2B. You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

Python Solution

from functools import lru_cache from typing import List def shoppingOffers(price: List[int], special: List[List[int]], needs: List[int]) -> int: n = len(price) filtered = [] for sp in special: cost = sp[-1] if cost < sum(sp[i] * price[i] for i in range(n)): filtered.append(sp) @lru_cache(None) def dfs(state): state = list(state) best = sum(state[i] * price[i] for i in range(n)) for sp in filtered: nxt = [] for i in range(n): if sp[i] > state[i]: break nxt.append(state[i] - sp[i]) else: best = min(best, sp[-1] + dfs(tuple(nxt))) return best return dfs(tuple(needs))

Complexity

The time complexity is O(n×k×mn)O(n \times k \times m^n)O(n×k×mn), where nnn represents the types of items, and kkk and mmm respectively represent the number of bundles and the maximum demand for each type of item. The space complexity is O(n×mn)O(n \times m^n)O(n×mn).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy