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:3squares are necessary to cover the rectangle.2(squares of1x1)1(square of2x2)
Example 2:

Input: n = 5, m = 8 Output: 5
Example 3:

Input: n = 11, m = 13 Output: 6
Constraints:
1 <= n, m <= 13Use dynamic programming to solve the problem by maintaining a DP table where each entry dp[i][j] represents the minimum number of squares needed to tile a rectangle of size i x j. The base case is straightforward with small squares, and we build up from there by iterating through each rectangle size up to n x m.
This Python function defines a DP table where dp[i][j] gives the minimum number of tiles to tile a rectangle of size i x j. We iterate through rectangle sizes and fill this table based on smaller subproblems, considering potential square tiles within it.
Java
C++
Time Complexity: O(n^3 * m^3) due to triple nested iteration and considering every possible sub-problem size.
Space Complexity: O(n * m) for storing the DP table.
This approach leverages recursion coupled with memorization to try placing the largest possible square within a rectangle and then recursively solve the remainder. The memorization helps optimize by storing previously computed results for specific rectangle dimensions.
This Python function recursively tries all possible square positions and sizes, and stores intermediate results in a memo dictionary to avoid recalculation. This significantly reduces the redundant computation.
Java
C#
JavaScript
Time Complexity: O(n^2 * m^2) due to recursive breakdown for subproblems within the range.
Space Complexity: O(n * m) due to memoization storage.
| Approach | Complexity |
|---|---|
| Dynamic Programming Approach | Time Complexity: O(n^3 * m^3) due to triple nested iteration and considering every possible sub-problem size. |
| Recursive Backtracking with Memorization | Time Complexity: O(n^2 * m^2) due to recursive breakdown for subproblems within the range. |
Detect Squares - Leetcode 2013 - Python #shorts • NeetCode • 485,887 views views
Watch 9 more video solutions →Practice Tiling a Rectangle with the Fewest Squares with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor