Program to find number of rectangles that can form the largest square in Python

Suppose we have an array called rect where rect[i] has two elements [len_i, wid_i], where len_i and wid_i are representing the length and width of ith rectangle respectively. Now we can cut the ith rectangle to form a square whose side length is of k if both k <= len_i and k <= wid_i. So for example, if we have a rectangle [4,6], then we can cut it to get a square with a side length of at most 4. Now consider a parameter called maxLen be the side length of the largest square we can get from any of the given rectangles. We have to find the number of rectangles that we can make a square with a side length of maxLen.

So, if the input is like rect = [[6,9],[4,10],[6,13],[17,6]], then the output will be 3 as we can get largest squares of sides [6, 4, 6, 6], so there are three rectangles which are largest.

Algorithm

To solve this, we will follow these steps ?

  • m := a new list

  • for each r in rect, do

    • insert minimum of r at the end of m

  • count (maximum of m) present in m and return

Example

Let us see the following implementation to get better understanding ?

def solve(rect):
    m = []
    for r in rect:
        m.append(min(r))
    
    return m.count(max(m))

rect = [[6,9],[4,10],[6,13],[17,6]]
print(solve(rect))

The output of the above code is ?

3

How It Works

The algorithm works by first finding the maximum possible square side length for each rectangle, which is the minimum of its length and width. For the given example:

  • Rectangle [6,9]: Maximum square side = min(6,9) = 6

  • Rectangle [4,10]: Maximum square side = min(4,10) = 4

  • Rectangle [6,13]: Maximum square side = min(6,13) = 6

  • Rectangle [17,6]: Maximum square side = min(17,6) = 6

The largest square side length is 6, and three rectangles can form this maximum square size.

Optimized Solution

We can solve this more efficiently without creating an intermediate list ?

def solve_optimized(rect):
    max_side = max(min(r) for r in rect)
    return sum(1 for r in rect if min(r) == max_side)

rect = [[6,9],[4,10],[6,13],[17,6]]
print(solve_optimized(rect))
3

Conclusion

The problem is solved by finding the minimum dimension of each rectangle (which represents the largest square it can form) and counting how many rectangles can form the maximum possible square. The optimized solution uses generator expressions to avoid creating intermediate lists, making it more memory-efficient.

Updated on: 2026-03-25T20:33:13+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements