Number of Ways of Cutting a Pizza (LeetCode 1444): Solution and Explanation
A rectangular pizza has some cells with apples. Make k - 1 cuts, each horizontal or vertical, giving away the top or left part every time, so that k pieces result. Count the ways to cut so that every piece has at least one apple, modulo 10^9 + 7.
Watch it run step by step
Try your own input and write the code →Intuition
Look at what remains after any sequence of cuts. Every horizontal cut removes rows from the top and every vertical cut removes columns from the left, so the piece we still hold is always a bottom-right sub-rectangle starting at some cell (i, j) and running to the corner. That means the whole state of the process is just the top-left corner of the remaining piece plus how many cuts are still to make. There are only m × n × k such states, even though the number of cut sequences is enormous.
From state (i, j, cuts), a horizontal cut at row ni gives away rows i to ni - 1 and leaves (ni, j, cuts - 1). A vertical cut at column nj gives away columns j to nj - 1 and leaves (i, nj, cuts - 1). A cut is only allowed if the part given away contains an apple. When no cuts remain, the leftover piece is the last slice, and it counts as one way if it has an apple. Summing over all valid cuts gives the recurrence, and memoization makes each state cost only its own loop.
The remaining question is how to test whether a strip has an apple without scanning it. Precompute apples[i][j], the number of apples in the rectangle from (i, j) to the bottom-right corner, using a suffix version of the 2D prefix sum. Then the apples in the rows cut away by a horizontal cut at ni are apples[i][j] - apples[ni][j], and similarly for vertical cuts. Each check is O(1).
Approach: Memoized DP with suffix apple counts
- Build
applesof size (m + 1) × (n + 1) from the bottom-right, usingapples[i][j] = cell + apples[i+1][j] + apples[i][j+1] - apples[i+1][j+1]. - Define
dp(i, j, cuts), the number of ways to cut the piece starting at(i, j)withcutscuts left. - If the piece has no apples, return 0. If
cutsis 0, return 1, since the piece itself is a valid final slice. - For each horizontal cut row
nifromi + 1to m - 1, adddp(ni, j, cuts - 1)whenapples[i][j] - apples[ni][j] > 0. - For each vertical cut column
njfromj + 1to n - 1, adddp(i, nj, cuts - 1)whenapples[i][j] - apples[i][nj] > 0. - Take the sum modulo 10^9 + 7 and return
dp(0, 0, k - 1).
Step-by-step example
pizza = ["A..", "AAA"], k = 3
- The suffix counts give
apples[0][0] = 4,apples[1][0] = 3,apples[0][1] = 2andapples[0][2] = 1. - From
dp(0, 0, 2), the only horizontal cut is at row 1. It gives away "A.." with 4 - 3 = 1 apple and leavesdp(1, 0, 1), the row "AAA". dp(1, 0, 1): a vertical cut at column 1 or column 2 each gives away an apple and leaves a piece with an apple, so this state has 2 ways.- A vertical cut at column 1 of the full pizza gives away 4 - 2 = 2 apples and leads to
dp(0, 1, 1). There, the horizontal cut would give away ".." with no apple, but a vertical cut at column 2 works, so it has 1 way. - A vertical cut at column 2 leaves only the last column, where the single remaining cut would give away an empty cell, so it contributes 0.
- The total is 2 + 1 + 0 = 3.
Code: Python, Java, C++
1class Solution:
2 def ways(self, pizza: List[str], k: int) -> int:
3 MOD = 10**9 + 7
4 m, n = len(pizza), len(pizza[0])
5
6 # Prefix sum of apples from (i,j) to bottom-right
7 apples = [[0] * (n + 1) for _ in range(m + 1)]
8 for i in range(m - 1, -1, -1):
9 for j in range(n - 1, -1, -1):
10 apples[i][j] = (pizza[i][j] == 'A') + apples[i + 1][j] + apples[i][j + 1] - apples[i + 1][j + 1]
11
12 @lru_cache(maxsize=None)
13 def dp(i, j, cuts):
14 if apples[i][j] == 0:
15 return 0
16 if cuts == 0:
17 return 1
18
19 ways = 0
20 # Horizontal cut
21 for ni in range(i + 1, m):
22 if apples[i][j] - apples[ni][j] > 0:
23 ways = (ways + dp(ni, j, cuts - 1)) % MOD
24 # Vertical cut
25 for nj in range(j + 1, n):
26 if apples[i][j] - apples[i][nj] > 0:
27 ways = (ways + dp(i, nj, cuts - 1)) % MOD
28 return ways
29
30 return dp(0, 0, k - 1)1class Solution {
2 private int MOD = 1_000_000_007;
3 private int[][] apples;
4 private int[][][] memo;
5 private int m, n;
6
7 public int ways(String[] pizza, int k) {
8 m = pizza.length;
9 n = pizza[0].length();
10 apples = new int[m + 1][n + 1];
11 memo = new int[m][n][k];
12 for (int[][] arr2d : memo) for (int[] arr : arr2d) Arrays.fill(arr, -1);
13
14 for (int i = m - 1; i >= 0; i--) {
15 for (int j = n - 1; j >= 0; j--) {
16 apples[i][j] = (pizza[i].charAt(j) == 'A' ? 1 : 0) + apples[i + 1][j] + apples[i][j + 1] - apples[i + 1][j + 1];
17 }
18 }
19
20 return dp(0, 0, k - 1);
21 }
22
23 private int dp(int i, int j, int cuts) {
24 if (apples[i][j] == 0) return 0;
25 if (cuts == 0) return 1;
26 if (memo[i][j][cuts] != -1) return memo[i][j][cuts];
27
28 int result = 0;
29 for (int ni = i + 1; ni < m; ni++) {
30 if (apples[i][j] - apples[ni][j] > 0) {
31 result = (result + dp(ni, j, cuts - 1)) % MOD;
32 }
33 }
34 for (int nj = j + 1; nj < n; nj++) {
35 if (apples[i][j] - apples[i][nj] > 0) {
36 result = (result + dp(i, nj, cuts - 1)) % MOD;
37 }
38 }
39 return memo[i][j][cuts] = result;
40 }
41}1class Solution {
2public:
3 int MOD = 1e9 + 7;
4 vector<vector<int>> apples;
5 vector<vector<vector<int>>> memo;
6 int m, n;
7
8 int ways(vector<string>& pizza, int k) {
9 m = pizza.size();
10 n = pizza[0].size();
11 apples.assign(m + 1, vector<int>(n + 1, 0));
12 memo.assign(m, vector<vector<int>>(n, vector<int>(k, -1)));
13
14 for (int i = m - 1; i >= 0; i--) {
15 for (int j = n - 1; j >= 0; j--) {
16 apples[i][j] = (pizza[i][j] == 'A') + apples[i + 1][j] + apples[i][j + 1] - apples[i + 1][j + 1];
17 }
18 }
19
20 return dp(0, 0, k - 1);
21 }
22
23 int dp(int i, int j, int cuts) {
24 if (apples[i][j] == 0) return 0;
25 if (cuts == 0) return 1;
26 if (memo[i][j][cuts] != -1) return memo[i][j][cuts];
27
28 int result = 0;
29 for (int ni = i + 1; ni < m; ni++) {
30 if (apples[i][j] - apples[ni][j] > 0) {
31 result = (result + dp(ni, j, cuts - 1)) % MOD;
32 }
33 }
34 for (int nj = j + 1; nj < n; nj++) {
35 if (apples[i][j] - apples[i][nj] > 0) {
36 result = (result + dp(i, nj, cuts - 1)) % MOD;
37 }
38 }
39 return memo[i][j][cuts] = result;
40 }
41};Time and space complexity
O(k × m × n × (m + n))
There are k × m × n states and each one loops over up to m + n cut positions with O(1) apple checks.
O(k × m × n)
The memoization cache holds one value per state, and the suffix sum table adds O(m × n).
Other approaches
Bottom-up DP over cut counts (time O(k × m × n × (m + n)), space O(m × n))
Fill a table dp[c][i][j] for c from 0 to k - 1, using the same transitions but iterating instead of recursing. It avoids recursion depth limits and lets you keep only two layers, cutting memory to O(m × n).
Common mistakes
- Checking whether the remaining piece has an apple but not the piece being given away. Both must be non-empty for the cut to count.
- Building a top-left prefix sum when the state is a bottom-right rectangle, which makes the subtraction formulas awkward and easy to get wrong.
- Forgetting the modulo inside the loop, which in Java or C++ overflows before the final reduction.
- Returning 1 at
cuts == 0without first checking that the last piece has an apple.
Frequently asked questions
Why is the remaining pizza always a bottom-right rectangle?
Each cut gives away either the top part or the left part. Removing rows from the top and columns from the left always leaves a rectangle that still touches the bottom-right corner.
Why use a suffix sum instead of a prefix sum?
The state is described by its top-left corner and extends to the bottom-right. A suffix sum stores exactly the apple count of that rectangle, so the count for the strip being cut away is a single subtraction.
Why is the answer taken modulo 10^9 + 7?
The number of valid cut sequences grows very quickly with the grid size and k. The modulus keeps the result in a fixed-size integer.