Tiling a Rectangle with the Fewest Squares - Problem

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

You need to find the optimal way to divide the rectangle into squares such that:

  • All squares have integer side lengths
  • The squares completely cover the rectangle without overlapping
  • The total number of squares is minimized

Example: A 2×3 rectangle can be tiled with 3 squares of size 1×1, or with other combinations, but we want the minimum count.

Input & Output

Example 1 — Square Case
$ Input: n = 2, m = 2
Output: 1
💡 Note: A 2×2 rectangle is already a perfect square, so we need only 1 square of size 2×2
Example 2 — Small Rectangle
$ Input: n = 2, m = 3
Output: 3
💡 Note: We can tile the 2×3 rectangle with 3 squares: one 2×2 square and two 1×1 squares, or three 2×1 rectangles each made of two 1×1 squares. The minimum is 3 squares total.
Example 3 — Larger Rectangle
$ Input: n = 5, m = 8
Output: 5
💡 Note: The 5×8 rectangle can be optimally tiled with 5 squares. One approach: one 5×5 square and four smaller squares to cover the remaining 5×3 area.

Constraints

  • 1 ≤ n, m ≤ 13
  • Answer will be a positive integer

Visualization

Tap to expand
Tiling 3×2 Rectangle with Minimum Squares3 × 2Original Rectangle2×21×11×1Optimal TilingResult: 3 squares minimumOne 2×2 square + Two 1×1 squares
Understanding the Visualization
1
Input
Rectangle of dimensions n × m
2
Process
Try all possible cuts to minimize square count
3
Output
Minimum number of squares needed
Key Takeaway
🎯 Key Insight: Use recursive cuts with memoization to avoid recalculating the same subproblems
Asked in
Google 15 Microsoft 12 Facebook 8
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen