#1725

Number Of Rectangles That Can Form The Largest Square

Easy
ArrayArrayGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution improves efficiency by combining the steps of finding the maximum square side length and counting the rectangles in a single pass. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize maxLen and count to 0.
  2. 2Step 2: Iterate through each rectangle, calculating the minimum side length (minSide).
  3. 3Step 3: If minSide is greater than maxLen, update maxLen and reset count to 1.
  4. 4Step 4: If minSide equals maxLen, increment the count.
solution.py16 lines
1# Full working Python code
2rectangles = [[5,8],[3,9],[5,12],[16,5]]
3
4def countRectangles(rectangles):
5    maxLen = 0
6    count = 0
7    for l, w in rectangles:
8        minSide = min(l, w)
9        if minSide > maxLen:
10            maxLen = minSide
11            count = 1
12        elif minSide == maxLen:
13            count += 1
14    return count
15
16print(countRectangles(rectangles))

Complexity note: This complexity is achieved because we only loop through the rectangles once, making it linear in relation to the number of rectangles.

  • 1The largest square side length is determined by the smallest dimension of the rectangles.
  • 2Counting rectangles that can form the largest square can be done in a single pass for efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.