Number Of Rectangles That Can Form The Largest Square - Problem

Imagine you're a carpenter working with various rectangular pieces of wood. You have an array rectangles where rectangles[i] = [li, wi] represents the length and width of the i-th rectangle.

From each rectangle, you can cut out a square with side length k, but only if both dimensions are at least k (i.e., k <= li and k <= wi). For example, from a [4,6] rectangle, you can cut a square with side length up to 4.

Your goal: Find the largest possible square you can cut from any rectangle, then count how many rectangles can produce a square of that maximum size.

Input: An array of rectangles with their dimensions
Output: The number of rectangles that can form the largest possible square

Input & Output

example_1.py โ€” Basic Case
$ Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]
โ€บ Output: 3
๐Ÿ’ก Note: The largest square we can cut is 5ร—5 from rectangles [5,8], [5,12], and [16,5]. Rectangle [3,9] can only make a 3ร—3 square, so it's not counted.
example_2.py โ€” All Same Size
$ Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]
โ€บ Output: 3
๐Ÿ’ก Note: Maximum square size is 3 (min dimension). Rectangles [2,3], [4,3], and [3,7] can all make a 3ร—3 square, while [3,7] appears twice but we count each occurrence.
example_3.py โ€” Single Rectangle
$ Input: rectangles = [[10,20]]
โ€บ Output: 1
๐Ÿ’ก Note: Only one rectangle exists, and it can make a 10ร—10 square (limited by the shorter dimension). So the count is 1.

Constraints

  • 1 <= rectangles.length <= 1000
  • rectangles[i].length == 2
  • 1 <= li, wi <= 109
  • All rectangle dimensions are positive integers

Visualization

Tap to expand
Rectangle โ†’ Square Conversion Process5 ร— 85ร—53 ร— 93ร—35 ร— 125ร—516 ร— 55ร—5Result: 3 rectangles can form the maximum 5ร—5 squareCount = 3
Understanding the Visualization
1
Identify Constraint
The maximum square size is limited by the rectangle's shorter dimension
2
Calculate Max Square
For each rectangle [l,w], max square = min(l,w)
3
Track Global Maximum
Find the largest square possible across all rectangles
4
Count Winners
Count how many rectangles can produce the maximum square
Key Takeaway
๐ŸŽฏ Key Insight: The maximum square from any rectangle is always limited by its shorter dimension - simply calculate min(length, width) for each rectangle!
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
24.5K Views
Medium Frequency
~8 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