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

Leetcode #1444: Number of Ways of Cutting a Pizza

In this guide, we solve Leetcode #1444 Number of Ways of Cutting a Pizza 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

Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Memoization, Array, Dynamic Programming, Matrix, Prefix Sum

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: pizza = ["A..","AAA","..."], k = 3 Output: 3 Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.

Python Solution

class Solution: def ways(self, pizza: List[str], k: int) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if k == 0: return int(s[m][n] - s[i][n] - s[m][j] + s[i][j] > 0) ans = 0 for x in range(i + 1, m): if s[x][n] - s[i][n] - s[x][j] + s[i][j] > 0: ans += dfs(x, j, k - 1) for y in range(j + 1, n): if s[m][y] - s[i][y] - s[m][j] + s[i][j] > 0: ans += dfs(i, y, k - 1) return ans % mod mod = 10**9 + 7 m, n = len(pizza), len(pizza[0]) s = [[0] * (n + 1) for _ in range(m + 1)] for i, row in enumerate(pizza, 1): for j, c in enumerate(row, 1): s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + int(c == 'A') return dfs(0, 0, k - 1)

Complexity

The time complexity is O(m×n×k×(m+n))O(m \times n \times k \times (m + n))O(m×n×k×(m+n)), and the space complexity is O(m×n×k)O(m \times n \times k)O(m×n×k). The space complexity is O(m×n×k)O(m \times n \times k)O(m×n×k).

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