</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Multi-dimensional DP

What is this?

Sometimes two indices are not enough because the answer also depends on a budget โ€” moves left, time elapsed, or items used. Multi-dimensional DP just adds that budget as one more axis of the table, so a state becomes dp[budget][row][col]. It is the same neighbor-spreading idea as a grid, with a counter ticking down each step, and you still remember every small answer so a given situation is solved only once. Think of a ball bouncing across a grid where you also care about how many moves remain.

flowchart TD A["Grid state row and col"] --> B["Add a budget axis k"] B --> C["Spread to neighbors and decrement k"] C --> D["Reuse solved smaller-budget states"] D --> E["Roll on the budget axis to save memory"]

๐Ÿ’ก Fun fact: Counting problems like these can produce astronomically large totals, so the answer is taken modulo 1,000,000,007 โ€” a prime chosen because it fits in a 32-bit integer and keeps every intermediate multiplication from overflowing.

๐Ÿ”“ The 1 problem in this chapter is free. Sign in with Google or Microsoft to start solving.


Core idea: Sometimes a 2D state isn't enough โ€” the answer also depends on a budget: moves remaining, time elapsed, items used. The fix is to add that quantity as another dimension of the DP, giving dp[budget][i][j]. The recurrence is the same idea as grid DP, just indexed by one more axis.


Add the axis the problem cares about

Grid DP dp[r][c] tracks position only; adding a budget gives dp[k][r][c] with k = moves/time/items remaining; the transition spreads to neighbors, decrementing k

The cost grows by a factor of the budget's range, but it's usually paid in iterations, not memory (you can roll on the budget axis).


The problem

Multi-dimensional DP: add the budget axis bucket pointing to its problem: Out of Boundary Paths

  • Out of Boundary Paths โ€” count ways a ball exits an mร—n grid within maxMove moves; the state is (moves-left, row, col) and off-grid transitions are exactly what you tally (mod 1e9+7).

Key takeaways

  • A budget/time constraint becomes a DP dimension โ€” dp[k][r][c].
  • Same neighbor-spreading recurrence as grid DP, decrementing the budget each step.
  • Roll on the budget axis to keep memory at O(mยทn).
  • Why interviewers love it: it tests whether you can identify all the state a transition truly depends on.

Problem: Out of Boundary Paths.

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.