We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Tiling a Rectangle with the Fewest Squares

Difficulty: Hard


Problem Description

Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.


Key Insights

  • The problem requires covering a rectangle using the least number of squares.
  • Squares can vary in size, up to the minimum dimension of the rectangle.
  • Backtracking is an appropriate approach since we can try different configurations of squares and backtrack if the current configuration doesn't lead to a solution.
  • The maximum size for n and m is 13, allowing for a brute-force or recursive solution with manageable complexity.

Space and Time Complexity

Time Complexity: O(n * m * min(n, m)) - We may explore all combinations of square placements. Space Complexity: O(n * m) - To maintain the state of the rectangle being covered.


Solution

The algorithm employs a backtracking approach to find the minimum number of squares needed to completely cover the rectangle. It tries to place squares of varying sizes, starting from the largest possible square that fits within the remaining area of the rectangle. It recursively attempts to fill the remaining space and keeps track of the minimum number of squares used.

  1. Start with the largest square that can fit in the current rectangle.
  2. Place the square and mark the covered area.
  3. Recursively attempt to cover the remaining uncovered area.
  4. If a configuration does not lead to a solution, backtrack and try a different configuration.
  5. Continue until the rectangle is completely covered and return the minimum count of squares used.

Code Solutions

def minSquares(n: int, m: int) -> int:
    def backtrack(n, m):
        if n == 0 or m == 0:
            return 0
        if n < m:
            n, m = m, n
        min_squares = float('inf')
        for size in range(1, m + 1):
            # Place a size x size square and cover the rest
            remaining_area1 = backtrack(n - size, m)
            remaining_area2 = backtrack(n, m - size)
            min_squares = min(min_squares, 1 + remaining_area1 + remaining_area2)
        return min_squares

    return backtrack(n, m)
← Back to All Questions