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 array strategy.
In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.
You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.
Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
Example 1:
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.
Example 2:
Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1] Output: 11 Explanation: The price of A is $2, and $3 for B, $4 for C. You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. You cannot add more items, though only $9 for 2A ,2B and 1C.
Constraints:
n == price.length == needs.length1 <= n <= 60 <= price[i], needs[i] <= 101 <= special.length <= 100special[i].length == n + 10 <= special[i][j] <= 50special[i][j] is non-zero for 0 <= j <= n - 1.Problem summary: In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Backtracking · Bit Manipulation
[2,5] [[3,0,5],[1,2,10]] [3,2]
[2,3,4] [[1,1,0,4],[2,2,1,9]] [1,2,1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #638: Shopping Offers
class Solution {
private final int bits = 4;
private int n;
private List<Integer> price;
private List<List<Integer>> special;
private Map<Integer, Integer> f = new HashMap<>();
public int shoppingOffers(
List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
n = needs.size();
this.price = price;
this.special = special;
int mask = 0;
for (int i = 0; i < n; ++i) {
mask |= needs.get(i) << (i * bits);
}
return dfs(mask);
}
private int dfs(int cur) {
if (f.containsKey(cur)) {
return f.get(cur);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += price.get(i) * (cur >> (i * bits) & 0xf);
}
for (List<Integer> offer : special) {
int nxt = cur;
boolean ok = true;
for (int j = 0; j < n; ++j) {
if ((cur >> (j * bits) & 0xf) < offer.get(j)) {
ok = false;
break;
}
nxt -= offer.get(j) << (j * bits);
}
if (ok) {
ans = Math.min(ans, offer.get(n) + dfs(nxt));
}
}
f.put(cur, ans);
return ans;
}
}
// Accepted solution for LeetCode #638: Shopping Offers
func shoppingOffers(price []int, special [][]int, needs []int) int {
const bits = 4
n := len(needs)
f := make(map[int]int)
mask := 0
for i, need := range needs {
mask |= need << (i * bits)
}
var dfs func(int) int
dfs = func(cur int) int {
if v, ok := f[cur]; ok {
return v
}
ans := 0
for i := 0; i < n; i++ {
ans += price[i] * ((cur >> (i * bits)) & 0xf)
}
for _, offer := range special {
nxt := cur
ok := true
for j := 0; j < n; j++ {
if ((cur >> (j * bits)) & 0xf) < offer[j] {
ok = false
break
}
nxt -= offer[j] << (j * bits)
}
if ok {
ans = min(ans, offer[n]+dfs(nxt))
}
}
f[cur] = ans
return ans
}
return dfs(mask)
}
# Accepted solution for LeetCode #638: Shopping Offers
class Solution:
def shoppingOffers(
self, price: List[int], special: List[List[int]], needs: List[int]
) -> int:
@cache
def dfs(cur: int) -> int:
ans = sum(p * (cur >> (i * bits) & 0xF) for i, p in enumerate(price))
for offer in special:
nxt = cur
for j in range(len(needs)):
if (cur >> (j * bits) & 0xF) < offer[j]:
break
nxt -= offer[j] << (j * bits)
else:
ans = min(ans, offer[-1] + dfs(nxt))
return ans
bits, mask = 4, 0
for i, need in enumerate(needs):
mask |= need << i * bits
return dfs(mask)
// Accepted solution for LeetCode #638: Shopping Offers
struct Solution;
use std::collections::HashMap;
impl Solution {
fn shopping_offers(price: Vec<i32>, special: Vec<Vec<i32>>, needs: Vec<i32>) -> i32 {
let n = price.len();
let m = special.len();
let mut memo: HashMap<Vec<i32>, i32> = HashMap::new();
memo.insert(vec![0; n], 0);
Self::dfs(needs, &mut memo, &price, &special, n, m)
}
fn dfs(
needs: Vec<i32>,
memo: &mut HashMap<Vec<i32>, i32>,
price: &[i32],
special: &[Vec<i32>],
n: usize,
m: usize,
) -> i32 {
if let Some(&res) = memo.get(&needs) {
return res;
}
let mut res: i32 = needs.iter().zip(price.iter()).map(|(a, b)| a * b).sum();
'special: for j in 0..m {
for i in 0..n {
if special[j][i] > needs[i] {
continue 'special;
}
}
let mut needs = needs.to_vec();
for i in 0..n {
needs[i] -= special[j][i];
}
res = res.min(Self::dfs(needs, memo, price, special, n, m) + special[j][n]);
}
memo.insert(needs, res);
res
}
}
#[test]
fn test() {
let price = vec![2, 5];
let special = vec_vec_i32![[3, 0, 5], [1, 2, 10]];
let needs = vec![3, 2];
let res = 14;
assert_eq!(Solution::shopping_offers(price, special, needs), res);
let price = vec![2, 3, 4];
let special = vec_vec_i32![[1, 1, 0, 4], [2, 2, 1, 9]];
let needs = vec![1, 2, 1];
let res = 11;
assert_eq!(Solution::shopping_offers(price, special, needs), res);
}
// Accepted solution for LeetCode #638: Shopping Offers
function shoppingOffers(price: number[], special: number[][], needs: number[]): number {
const bits = 4;
const n = needs.length;
const f: Map<number, number> = new Map();
let mask = 0;
for (let i = 0; i < n; i++) {
mask |= needs[i] << (i * bits);
}
const dfs = (cur: number): number => {
if (f.has(cur)) {
return f.get(cur)!;
}
let ans = 0;
for (let i = 0; i < n; i++) {
ans += price[i] * ((cur >> (i * bits)) & 0xf);
}
for (const offer of special) {
let nxt = cur;
let ok = true;
for (let j = 0; j < n; j++) {
if (((cur >> (j * bits)) & 0xf) < offer[j]) {
ok = false;
break;
}
nxt -= offer[j] << (j * bits);
}
if (ok) {
ans = Math.min(ans, offer[n] + dfs(nxt));
}
}
f.set(cur, ans);
return ans;
};
return dfs(mask);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
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.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.