#1240

Tiling a Rectangle with the Fewest Squares

Hard
BacktrackingDynamic ProgrammingBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m * min(n, m))
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m * min(n, m))Space O(n * m)

The optimal solution uses dynamic programming to store the minimum number of squares needed for each sub-rectangle. This avoids redundant calculations and significantly speeds up the process.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a DP array where dp[i][j] represents the minimum number of squares needed for a rectangle of size i x j.
  2. 2Step 2: Initialize dp[i][i] = 1 for all i, as a square can fill a square rectangle.
  3. 3Step 3: For each rectangle size, iterate through all possible square placements, updating the DP array with the minimum count found.
  4. 4Step 4: Return dp[n][m] as the result.
solution.py10 lines
1def minSquares(n, m):
2    dp = [[float('inf')] * (m + 1) for _ in range(n + 1)]
3    for i in range(1, n + 1):
4        for j in range(1, m + 1):
5            if i == j:
6                dp[i][j] = 1
7            else:
8                for k in range(1, min(i, j) + 1):
9                    dp[i][j] = min(dp[i][j], 1 + dp[i - k][j], 1 + dp[i][j - k])
10    return dp[n][m]

Complexity note: The time complexity is O(n * m * min(n, m)) because we fill a DP table of size n x m, and for each cell, we may iterate through the minimum dimension to find the best square placement.

  • 1Understanding how to break down the rectangle into smaller squares is crucial.
  • 2Dynamic programming helps avoid redundant calculations and speeds up the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.