391. Perfect Rectangle
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to determine if a given set of axis-aligned rectangles can perfectly tile a larger rectangular region. A perfect tiling means there are no overlaps between the small rectangles and no gaps within the larger rectangle they form.
Solution
Perfect Rectangle in Python
class Solution:
def isRectangleCover(self, rectangles: list[list[int]]) -> bool:
total_area = 0
min_x, min_y = float('inf'), float('inf')
max_x, max_y = float('-inf'), float('-inf')
# Use a set of tuples to store corner points
points = set()
for rect in rectangles:
x1, y1, x2, y2 = rect[0], rect[1], rect[2], rect[3]
# Calculate total area and find the bounding box
total_area += (x2 - x1) * (y2 - y1)
min_x = min(min_x, x1)
min_y = min(min_y, y1)
max_x = max(max_x, x2)
max_y = max(max_y, y2)
# Four corners of the rectangle
p1 = (x1, y1)
p2 = (x1, y2)
p3 = (x2, y1)
p4 = (x2, y2)
# Toggle the presence of each corner point in the set
for p in [p1, p2, p3, p4]:
if p in points:
points.remove(p)
else:
points.add(p)
# Condition 1: The total area of small rectangles must equal the area of the bounding box.
expected_area = (max_x - min_x) * (max_y - min_y)
if total_area != expected_area:
return False
# Condition 2: Exactly four corner points should remain, and they must be the corners of the bounding box.
if len(points) != 4:
return False
# Verify that the remaining points are the corners of the bounding box
bounding_box_corners = set([(min_x, min_y), (min_x, max_y), (max_x, min_y), (max_x, max_y)])
if points != bounding_box_corners:
return False
return True
Perfect Rectangle in Java
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
long totalArea = 0;
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
// Use a set of strings to store corner points. E.g., "x,y"
Set<String> points = new HashSet<>();
for (int[] rect : rectangles) {
int x1 = rect[0];
int y1 = rect[1];
int x2 = rect[2];
int y2 = rect[3];
// Calculate total area and find the bounding box
totalArea += (long)(x2 - x1) * (y2 - y1);
minX = Math.min(minX, x1);
minY = Math.min(minY, y1);
maxX = Math.max(maxX, x2);
maxY = Math.max(maxY, y2);
// Four corners of the rectangle
String p1 = x1 + "," + y1;
String p2 = x1 + "," + y2;
String p3 = x2 + "," + y1;
String p4 = x2 + "," + y2;
// Toggle the presence of each corner point in the set
if (!points.add(p1)) points.remove(p1);
if (!points.add(p2)) points.remove(p2);
if (!points.add(p3)) points.remove(p3);
if (!points.add(p4)) points.remove(p4);
}
// Condition 1: The total area of small rectangles must equal the area of the bounding box.
long expectedArea = (long)(maxX - minX) * (maxY - minY);
if (totalArea != expectedArea) {
return false;
}
// Condition 2: Exactly four corner points should remain, and they must be the corners of the bounding box.
if (points.size() != 4) {
return false;
}
if (!points.contains(minX + "," + minY) ||
!points.contains(minX + "," + maxY) ||
!points.contains(maxX + "," + minY) ||
!points.contains(maxX + "," + maxY)) {
return false;
}
return true;
}
}
Perfect Rectangle in C++
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
long long total_area = 0;
int min_x = INT_MAX, min_y = INT_MAX;
int max_x = INT_MIN, max_y = INT_MIN;
// Using std::set for points to handle pairs easily. An unordered_set with a custom hash would be faster.
set<pair<int, int>> points;
for (const auto& rect : rectangles) {
int x1 = rect[0];
int y1 = rect[1];
int x2 = rect[2];
int y2 = rect[3];
// Calculate total area and find the bounding box
total_area += (long long)(x2 - x1) * (y2 - y1);
min_x = min(min_x, x1);
min_y = min(min_y, y1);
max_x = max(max_x, x2);
max_y = max(max_y, y2);
// Four corners of the rectangle
pair<int, int> p1 = {x1, y1};
pair<int, int> p2 = {x1, y2};
pair<int, int> p3 = {x2, y1};
pair<int, int> p4 = {x2, y2};
// Toggle the presence of each corner point in the set
if (points.count(p1)) points.erase(p1); else points.insert(p1);
if (points.count(p2)) points.erase(p2); else points.insert(p2);
if (points.count(p3)) points.erase(p3); else points.insert(p3);
if (points.count(p4)) points.erase(p4); else points.insert(p4);
}
// Condition 1: The total area of small rectangles must equal the area of the bounding box.
if (total_area != (long long)(max_x - min_x) * (max_y - min_y)) {
return false;
}
// Condition 2: Exactly four corner points should remain, and they must be the corners of the bounding box.
if (points.size() != 4) {
return false;
}
if (points.find({min_x, min_y}) == points.end() ||
points.find({min_x, max_y}) == points.end() ||
points.find({max_x, min_y}) == points.end() ||
points.find({max_x, max_y}) == points.end()) {
return false;
}
return true;
}
};
Perfect Rectangle in TypeScript
function isRectangleCover(rectangles: number[][]): boolean {
let totalArea = 0;
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
// Use a Set of strings to store corner points, e.g., "x,y"
const points = new Set<string>();
for (const rect of rectangles) {
const x1 = rect[0];
const y1 = rect[1];
const x2 = rect[2];
const y2 = rect[3];
// Calculate total area and find the bounding box
// Using BigInt for area to avoid potential overflow with large coordinates, although JS numbers have a large safe range.
totalArea += (x2 - x1) * (y2 - y1);
minX = Math.min(minX, x1);
minY = Math.min(minY, y1);
maxX = Math.max(maxX, x2);
maxY = Math.max(maxY, y2);
// Four corners of the rectangle
const p1 = `${x1},${y1}`;
const p2 = `${x1},${y2}`;
const p3 = `${x2},${y1}`;
const p4 = `${x2},${y2}`;
// Toggle the presence of each corner point in the set
for (const p of [p1, p2, p3, p4]) {
if (points.has(p)) {
points.delete(p);
} else {
points.add(p);
}
}
}
// Condition 1: The total area of small rectangles must equal the area of the bounding box.
const expectedArea = (maxX - minX) * (maxY - minY);
if (totalArea !== expectedArea) {
return false;
}
// Condition 2: Exactly four corner points should remain, and they must be the corners of the bounding box.
if (points.size !== 4) {
return false;
}
if (!points.has(`${minX},${minY}`) ||
!points.has(`${minX},${maxY}`) ||
!points.has(`${maxX},${minY}`) ||
!points.has(`${maxX},${maxY}`)) {
return false;
}
return true;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.