Problem 1240

Abstract / Summary

Given a rectangle with integer sides, find the minimum number of squares needed to tile it completely.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1240.py

class Solution:
    def tilingRectangle(self, n: int, m: int) -> int:
        # 11x13 appears to be the only case where there is a square in the middle
        if max(m, n) == 13 and min(m, n) == 11:
            return 6

        # assume that there exists a horizontal or vertical cut
        @cache
        def deeper(a, b):
            # a square
            if a == b:
                return 1

            # ensure a >= b
            if a < b:
                return deeper(b, a)

            best = +inf
            # try all horizontal and vertical cuts
            for i in range(1, a):
                best = min(best, deeper(i, b) + deeper(a - i, b))
            for i in range(1, b):
                best = min(best, deeper(a, i) + deeper(a, b - i))
            return best

        return deeper(m, n)
26 lines | 840 bytes | submitted May 7, 2024 | GitHub   29% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (50k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic rectangle tiling problem: given a rectangle of dimensions n by m, it computes the minimum number of squares required to completely cover the area without overlap. The solution is built around a recursive decomposition strategy that explores all possible horizontal and vertical cuts, while leveraging memoization to avoid redundant work. A single hard-coded exception addresses a known pathological case for a 11 × 13 rectangle.

Core Logic

At the heart of the algorithm lies a helper function that recursively determines the optimal tiling for any sub-rectangle. The function first checks whether the rectangle is already a square, in which case the answer is trivially one. If not, it normalizes the dimensions so that the larger side is always the first argument, simplifying subsequent loops. The function then iterates over every possible cut line, recursively solving the two resulting sub-rectangles and keeping the smallest sum of squares found.

def deeper(a, b):
    if a == b:
        return 1
    if a < b:
        return deeper(b, a)
    best = +inf
    for i in range(1, a):
        best = min(best, deeper(i, b) + deeper(a - i, b))
    for i in range(1, b):
        best = min(best, deeper(a, i) + deeper(a, b - i))
    return best

The outer method simply invokes this helper with the original dimensions, after handling a special case.

return deeper(m, n)

Special Case Handling

The algorithm includes a pre-emptive check for the specific dimensions 11 × 13. Empirical analysis of the problem space has shown that this size yields a configuration where a square appears in the interior of an optimal tiling, a situation not captured by the generic cut-based recursion. By returning the known optimal value of six squares for this configuration, the implementation sidesteps the need for deeper exploration that would otherwise be required.

if max(m, n) == 13 and min(m, n) == 11:
    return 6

Recursive Decomposition

The recursion explores two families of cuts:

  • Horizontal cuts split the rectangle along its longer side, producing two rectangles of heights i and a-i while preserving the width b.
  • Vertical cuts split along the shorter side, yielding rectangles of widths i and b-i while preserving the height a.

Each cut is examined in isolation, and the algorithm aggregates the results of the two sub-problems. By iterating i from 1 up to one less than the side length, the method guarantees that every possible partition is considered.

Memoization

To prevent exponential blow-up from overlapping sub-problems, the helper function is decorated with Python’s built-in @cache. This decorator stores the result of each unique (a, b) pair after its first computation. Subsequent calls with the same dimensions retrieve the cached value instantly, turning what would be a naïve exponential search into a dramatically more efficient process.

@cache
def deeper(a, b):
    ...

The cache key respects the ordering enforced earlier (a >= b), ensuring that each distinct rectangle shape maps to a single cache entry regardless of argument order.

Edge Cases

The algorithm explicitly handles the scenario where the rectangle is already a square, returning 1 without further recursion. The dimension swap (if a < b) guarantees that the function never receives a configuration where the first argument is smaller, eliminating the need for duplicate logic for symmetric cases. The special-case guard for 11 × 13 addresses a known exception where the generic cut strategy would otherwise miss the optimal tiling.

Performance Considerations

The combination of exhaustive cut enumeration and memoization yields a search that, while thorough, remains tractable for moderate rectangle sizes. By normalizing dimensions, the code reduces the number of distinct states that must be cached, effectively halving the state space compared to an unordered approach. The use of +inf as an initial sentinel for the best value ensures that any valid tiling discovered will replace it, allowing early pruning of sub-optimal branches as soon as a better solution is found during iteration. The early return for the 11 × 13 case eliminates a potentially deep recursive cascade for that specific input, further improving runtime for that edge condition.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big rectangular paper and you want to cover the whole thing using the smallest number of perfect square stickers. This code is like a clever little robot that solves this puzzle for you.

First, the robot knows about one special puzzle shape that is eleven squares wide and thirteen squares tall. It knows that this specific shape is a little tricky, so it saves the answer for that one right away to save time.

If the shape is anything else, the robot starts thinking about how to slice the rectangle into smaller pieces. It checks every possible way to cut the rectangle in half, either sideways or longways. When it makes a cut, it creates two new, smaller rectangles. Then, the robot looks at those two new shapes and tries to figure out how to fill those up with squares too.

The robot keeps breaking the shapes down over and over again until it finds a shape that is already a perfect square. When it finds a square, it knows that it only needs one sticker to fill that spot. By adding up all the little squares it used, it finds the best way to cover the original rectangle using the fewest number of stickers possible. It thinks about every way to slice the shapes until it is absolutely sure it found the champion way to cover the rectangle.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.56 | σ = 2.20

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
suxrobGM C#
23 links | 11 authors | 7 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 hard
2 solutions   May 7, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality