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 a Rectangle with the Fewest Squares INPUT 2 x 2 Rectangle n = 2 (width) m = 2 (height) Input Parameters: n = 2 m = 2 Integer-sided squares ALGORITHM STEPS 1 Check if Square If n == m, return 1 2 Compare Dimensions n=2, m=2 --> Equal! 3 Apply Base Case Perfect square found 4 Return Result Minimum squares = 1 Decision Logic: n == m ? YES return 1 FINAL RESULT 1 Square (2x2) OK Output: 1 Minimum number of squares Key Insight: When a rectangle has equal dimensions (n == m), it is already a perfect square. This is the base case - only 1 square is needed. For non-square rectangles, use recursion/DP to find optimal tiling by trying all possible square placements. TutorialsPoint - Tiling a Rectangle with the Fewest Squares | Optimal Solution
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