Leetcode 1725. Number Of Rectangles That Can Form The Largest Square
You are given an array of rectangles represented by a 2D array rectangles
where rectangles[i] = [li, wi]
denotes the length and width of the i
-th rectangle. You need to find the number of rectangles that can form the largest square.
A rectangle can form a square if and only if at least one of its sides is the length of the largest square possible.
rectangles
array?Given rectangles = [[2, 3], [3, 7], [4, 3], [3, 3]]
, the output should be 3. This is because the largest square possible is of side 3, and there are three rectangles that can form this square: [3, 7], [4, 3], [3, 3]
.
li
and wi
for each rectangle.The time complexity for this approach is O(n), where n is the number of rectangles. We iterate through the list twice: once to find the maximum side length and once to count the rectangles that can form a square with that side length.
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
public:
int countGoodRectangles(vector<vector<int>>& rectangles) {
int maxLen = 0;
// Step 1: Find the longest possible side length of a square
for (const auto& rectangle : rectangles) {
int sideLen = min(rectangle[0], rectangle[1]);
maxLen = max(maxLen, sideLen);
}
// Step 2: Count how many rectangles can form the largest square
int count = 0;
for (const auto& rectangle : rectangles) {
if (min(rectangle[0], rectangle[1]) == maxLen) {
++count;
}
}
return count;
}
};
int main() {
Solution sol;
vector<vector<int>> rectangles1 = \{\{2, 3}, {3, 7}, {4, 3}, {3, 3}};
cout << sol.countGoodRectangles(rectangles1) << endl; // Output: 3
vector<vector<int>> rectangles2 = \{\{5, 8}, {3, 9}, {5, 12}, {16, 5}};
cout << sol.countGoodRectangles(rectangles2) << endl; // Output: 3
return 0;
}
min(li, wi)
.This approach ensures we efficiently find and count the rectangles capable of forming the largest possible square.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?