Number Of Rectangles That Can Form The Largest Square - Problem

You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.

You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.

Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.

Return the number of rectangles that can make a square with a side length of maxLen.

Input & Output

Example 1 — Basic Case
$ Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]
Output: 3
💡 Note: The largest square you can cut from each rectangle: [5,8]→5, [3,9]→3, [5,12]→5, [16,5]→5. The largest square size is 5, and 3 rectangles can form this size.
Example 2 — All Same Size
$ Input: rectangles = [[2,3],[3,7],[4,3]]
Output: 2
💡 Note: Maximum square sizes: [2,3]→2, [3,7]→3, [4,3]→3. The largest square size is 3, and 2 rectangles ([3,7] and [4,3]) can form this size.
Example 3 — Single Rectangle
$ Input: rectangles = [[10,20]]
Output: 1
💡 Note: Only one rectangle [10,20] can form a square of size min(10,20)=10. So 1 rectangle can form the maximum square.

Constraints

  • 1 ≤ rectangles.length ≤ 1000
  • rectangles[i].length == 2
  • 1 ≤ li, wi ≤ 109

Visualization

Tap to expand
Number Of Rectangles That Can Form Largest Square INPUT rectangles array: 5x8 [5,8] min=5 3x9 [3,9] min=3 5x12 [5,12] min=5 16x5 [16,5] min=5 rectangles = [[5,8],[3,9], [5,12],[16,5]] Max square from each rect: min(l,w) for each 5 3 5 5 squares ALGORITHM STEPS 1 Initialize Variables maxLen = 0, count = 0 2 Single Pass Loop For each rectangle: 3 Find Min Side side = min(length, width) 4 Update maxLen/count Track largest and count Processing: [5,8] min=5 maxLen=5 cnt=1 [3,9] min=3 maxLen=5 cnt=1 [5,12] min=5 maxLen=5 cnt=2 [16,5] min=5 maxLen=5 cnt=3 Final: 3 FINAL RESULT Largest square side: maxLen = 5 3 rectangles can form 5x5 square: 5 [5,8] 5 [5,12] 5 [16,5] Excluded (max square = 3): 3 [3,9] Output: 3 rectangles with maxLen=5 Key Insight: The largest square that can be cut from a rectangle is limited by its shorter side (min of length, width). Single-pass approach: Track maxLen and count simultaneously. If current min equals maxLen, increment count. If current min exceeds maxLen, update maxLen and reset count to 1. Time: O(n), Space: O(1). TutorialsPoint - Number Of Rectangles That Can Form The Largest Square | Single-Pass Approach
Asked in
Google 15 Amazon 12 Microsoft 8
27.7K Views
Medium Frequency
~10 min Avg. Time
867 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