Leetcode #1240: Tiling a Rectangle with the Fewest Squares
In this guide, we solve Leetcode #1240 Tiling a Rectangle with the Fewest Squares 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.

Problem Statement
Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle. Example 1: Input: n = 2, m = 3 Output: 3 Explanation: 3 squares are necessary to cover the rectangle.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Python Solution
class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
def dfs(i: int, j: int, t: int):
nonlocal ans
if j == m:
i += 1
j = 0
if i == n:
ans = t
return
if filled[i] >> j & 1:
dfs(i, j + 1, t)
elif t + 1 < ans:
r = c = 0
for k in range(i, n):
if filled[k] >> j & 1:
break
r += 1
for k in range(j, m):
if filled[i] >> k & 1:
break
c += 1
mx = r if r < c else c
for w in range(1, mx + 1):
for k in range(w):
filled[i + w - 1] |= 1 << (j + k)
filled[i + k] |= 1 << (j + w - 1)
dfs(i, j + w, t + 1)
for x in range(i, i + mx):
for y in range(j, j + mx):
filled[x] ^= 1 << y
ans = n * m
filled = [0] * n
dfs(0, 0, 0)
return ans
Complexity
The time complexity is Exponential (worst case). The space complexity is O(depth).
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.