Back to challenges
Hard 0 solved 0% acceptance

Cut a Rectangle Into Squares

Find the fewest straight cuts needed to produce only squares.

What you'll learn

  • Define a DP table over width and height
  • Try every horizontal and vertical cut
  • Reuse results for smaller rectangles

Problem

On each move, choose one rectangle and cut all the way across it, parallel to a side, making two rectangles with positive integer side lengths. Continue until every piece is a square. Squares may have different sizes. Count cuts, not pieces.

Implement rectangle_cutting(height, width).

Input

height: The starting rectangle height.

width: The starting rectangle width.

Output

Return the minimum number of cuts.

Constraints

1 ≤ height, width ≤ 500. Rotation does not change the answer.

Examples

Example 1
Input:
width = 3
height = 2

Expected output:
expected = 2
Input:
long long width = 3;
long long height = 2;

Expected output:
long long expected = 2;
Input:
long width = 3;
long height = 2;

Expected output:
long expected = 2;

Explanation

Cut off a 2 × 2 square, leaving a 2 × 1 rectangle. One more cut splits the remainder into two unit squares.

Example 2
Input:
width = 4
height = 4

Expected output:
expected = 0
Input:
long long width = 4;
long long height = 4;

Expected output:
long long expected = 0;
Input:
long width = 4;
long height = 4;

Expected output:
long expected = 0;

Explanation

The starting rectangle is already a square.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

A rectangle can be solved by splitting it into two smaller rectangles and combining their best answers.

Hint 2

Try every possible horizontal and vertical cut to find the minimum.

Hint 3

Memoization or a table is helpful because many subrectangles repeat.

Expected complexity

O(h*w*(h+w)) time, O(h*w) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.