Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A pricing team wrote a recursive DP over product bundles that takes 40 minutes per run and now must run per request. How would you approach making this feasible?

We first profile the state space to learn how many states exist, how many are reachable and which are equivalent, because the 40 minutes usually come from redundant states and heavy keys. Then we memoize with compact keys such as encoded longs instead of objects in a HashMap, or convert to bottom-up arrays. Results for common inputs are precomputed offline and cached so a request only computes the delta, approximations with an agreed error bound are considered with the product owners, and if the problem is really constrained optimisation, an integer programming solver may do better than hand-written DP.

Why this question is asked

A pricing algorithm that runs as a nightly batch can be slow and nobody minds. The moment it has to run inside a request, with a budget of maybe 200 milliseconds, it needs to be about ten thousand times faster. Interviewers ask this scenario because there is no single trick: the answer is a disciplined process of measuring, removing waste, moving work out of the request path, and questioning the requirement itself. In this answer, we will set the target, profile the state space, make the memoization cheap, move work offline with caching, consider approximations, and look at when a solver is the right tool.

1Setting the Target

Forty minutes is 2,400 seconds. If the request budget is 200 milliseconds, we need a speedup of 12,000 times. That number is useful because it tells us immediately that tuning alone, a faster JVM flag or a parallel stream, will not be enough. Parallelism on 16 cores gives at most 16 times. We need to remove work, not do the same work faster. It also tells us to ask early whether the request really needs the exact answer, or whether a cached or slightly approximate answer would be acceptable, because that changes the whole design.

2Profiling the State Space

Dynamic programming cost is the number of distinct states times the work per state. So the first job is to understand the states. A state here might be (bundle position, items already chosen, remaining budget, applied discounts). We add counters to the existing code: how many calls, how many distinct states, how many cache hits. A profiler such as async-profiler shows where the time goes. Typical findings are that most of the time is in hashing and allocating state objects rather than in pricing logic, that many states are unreachable under real business rules, and that many states are symmetric: choosing item A then B gives the same state as B then A.

Each finding shrinks the work. Pruning unreachable states with business constraints, such as a maximum bundle size of 5, can cut the state count by orders of magnitude. Canonicalising symmetric states, for example by storing the chosen set as a sorted bitmask instead of an ordered list, merges duplicates. We measure the state count again after each change.

Step throughA process for making the DP feasible
  1. Measure states, calls, hit ratecounters and async-profiler
  2. Prune and canonicalise statesbusiness limits, symmetry
  3. Compact memo keys or bottom-up arraysno objects in the hot path
  4. Fast enough per request?
    YesShip with a latency budgetNoPrecompute and cache
  5. Still too slow or too large?
    YesDiscuss approximation or a solverNoDone

5 steps in order. Play them, or step through them one at a time.

3Memoization With Compact Keys

Recursive DP code often memoizes with a HashMap<State, Result> where State is a class or, worse, a List or String built for every call. Every lookup then allocates, hashes several fields, and calls equals, and millions of state objects stress the garbage collector. If the state fits in 64 bits, we can encode it into a long and use a primitive map, or, if the dimensions are small and dense, index a flat array directly.

Java
// Before: allocates a key object for every call
record State(int pos, Set<Integer> chosen, int budget) {}
Map<State, Long> memo = new HashMap<>();
// After: pos < 4096, chosen as a bitmask of up to 32 items, 0 <= budget < 2^20
static long key(int pos, int chosenMask, int budget) {
return ((long) pos << 52)
| (Integer.toUnsignedLong(chosenMask) << 20) // unsigned: no sign extension
| budget; // one long, no allocation
}
Long2LongOpenHashMap memo2 = new Long2LongOpenHashMap(); // fastutil primitive map
memo2.defaultReturnValue(-1);
// Or bottom-up, when every state is reachable and the dimensions are small:
long[][] best = new long[positions + 1][budgetSteps + 1];

Notice that the encoded key must fit exactly: the bit widths have to be checked against real limits, with an assertion that fails loudly if a dimension grows. Converting to bottom-up arrays also removes recursion and its stack depth limit, and array access is far faster than hashing. Changes like these commonly give one or two orders of magnitude, but on their own they rarely reach 12,000 times.

4Precomputing Offline and Serving From a Cache

The biggest win usually comes from not computing in the request at all. Pricing inputs are rarely all unique: if 80 percent of requests use one of a few thousand common bundle configurations, a nightly or hourly job can compute those results with the existing algorithm and store them in a key-value store or an in-memory cache keyed by a canonical description of the input. The request path becomes a lookup.

For the remaining requests, we look for structure that allows a delta. If a request differs from a precomputed case by one item or one discount, the DP can often start from the stored intermediate table and recompute only the affected part. When even that is too slow, the request can return the nearest precomputed price with a flag and refine asynchronously, if the business accepts that. Cache invalidation follows price list changes: when a catalog version changes, the precompute job runs for the new version and the key includes the version, so stale entries are never served.

Step throughWhere the work moves
  1. Request pathcanonical key -> cache lookup, about 1 ms
  2. Delta computationstart from stored table, small DP per request
  3. Precompute jobhourly or on catalog change, existing algorithm
  4. Cache keyed by catalog versionold versions expire, never served stale

4 layers, from the top down. Step through them one at a time.

5Approximations and Heuristics, Agreed With Product

If exact optimality is not essential, there are faster options. We can coarsen a dimension, such as pricing the budget in steps of 1 dollar instead of 1 cent, which divides that dimension by 100. We can cap the search with beam search, keeping only the best 1,000 partial solutions at each step. Or we can use a greedy heuristic with a known worst case. Each of these produces an error, and the important step is to measure it on real historical requests, for example 'the heuristic price is within 0.5 percent of optimal for 99 percent of requests', and agree with the product owners whether that is acceptable. That decision belongs to the business, not to the engineer alone, because it affects revenue and customer trust.

6When a Solver Is the Better Tool

Bundle pricing with constraints, such as at most one of these items, a minimum margin, and discounts that interact, is often an integer programming problem in disguise. Mixed integer programming solvers, such as Google OR-Tools with its CP-SAT solver, or commercial solvers such as Gurobi, use decades of research in pruning, bounding and presolving, and can solve such models in milliseconds where a hand-written DP explores every state. They also give a provable bound on how far a time-limited answer is from optimal.

The cost is modelling skill and, for commercial solvers, licence fees. I would prototype the model with OR-Tools on a sample of real inputs and compare solve times and answers with the existing DP before committing. Whatever we choose, I would protect the request path with a strict time limit and a fallback, such as a cached price, so a hard input cannot cause a timeout.

7Follow-up questions

How do you know the optimised version still gives the same prices?

We keep the original slow implementation as a reference oracle and run both on thousands of recorded inputs, plus generated edge cases, in a test that compares results exactly. Any difference blocks the change until we understand it.

Would rewriting it in C++ solve the problem?

Not by itself. A language change gives maybe two to five times on this kind of code, while we need four orders of magnitude. Removing redundant states and moving work out of the request path are what close that gap.

What if the inputs are too varied to cache?

Then we rely on state reduction, compact memoization, approximation with an agreed error, or a solver with a time limit. We also check whether parts of the input are independent, because splitting a bundle into independent groups turns one large state space into several small ones.

8Conclusion

In this answer, we turned a 40 minute DP into something that can run per request by setting a numeric target, profiling the state space to prune unreachable and symmetric states, replacing object keys with encoded longs or bottom-up arrays, precomputing common inputs offline and computing only deltas in the request, agreeing on approximations with bounded error with the product owners, and considering an integer programming solver when the problem is really constrained optimisation.

What to say in the interviewAbout 100 seconds aloud

Open with

I would start by quantifying the gap. Forty minutes against a request budget of a couple of hundred milliseconds is roughly a twelve thousand times speedup, so tuning or more cores will not do it; we have to remove work.

Then, if they want more

First I would profile the state space: count calls, distinct states and cache hits, and run a profiler. Usually I find that many states are unreachable under business rules, many are symmetric, like choosing A then B versus B then A, and much of the time is spent hashing and allocating state objects.

So I would prune with real limits, canonicalise states as sorted bitmasks, and memoize with keys encoded into a long in a primitive map, or go bottom-up with arrays when the dimensions are dense. That typically gives one or two orders of magnitude.

The bigger win is to move work out of the request: precompute the common configurations offline per catalog version, serve them from a cache, and compute only the delta for unusual requests.

If that is still not enough, I would discuss approximation with product, for example coarser price steps or beam search, with the error measured on real requests and agreed explicitly.

And if the problem is really constrained optimisation, I would prototype it with a solver like OR-Tools, keep the old code as a reference oracle in tests, and always protect the request with a time limit and a cached fallback.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A pricing team wrote a recursive DP over product bundles that takes 40 minutes per run...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/a1207dcd9d/