LeetCode 391: Perfect Rectangle Solution
Master LeetCode problem 391 (Perfect Rectangle), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
391. Perfect Rectangle
Problem Explanation
Explanation:
The problem requires us to determine if a given set of rectangles forms an exact cover of a rectangular region. An exact cover means that each point within the region is covered by exactly one rectangle and no extra points are covered. To solve this problem, we can follow these steps:
- Calculate the total area covered by all rectangles and also keep track of the corners of each rectangle.
- The sum of areas of individual rectangles should be equal to the total area covered by all rectangles.
- Ensure that all corner points (bottom-left and top-right) of each rectangle are unique and appear an even number of times (except for the four corners of the overall bounding rectangle).
Time complexity: O(n), where n is the number of rectangles. Space complexity: O(n)
:
Solution Code
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
int area = 0;
Set<String> corners = new HashSet<>();
for (int[] rect : rectangles) {
area += (rect[2] - rect[0]) * (rect[3] - rect[1]);
String bottomLeft = rect[0] + "," + rect[1];
String bottomRight = rect[2] + "," + rect[1];
String topLeft = rect[0] + "," + rect[3];
String topRight = rect[2] + "," + rect[3];
if (!corners.add(bottomLeft)) corners.remove(bottomLeft);
if (!corners.add(bottomRight)) corners.remove(bottomRight);
if (!corners.add(topLeft)) corners.remove(topLeft);
if (!corners.add(topRight)) corners.remove(topRight);
}
if (corners.size() != 4 || !corners.containsAll(Arrays.asList(rectangles[0][0] + "," + rectangles[0][1],
rectangles[0][2] + "," + rectangles[0][1],
rectangles[0][0] + "," + rectangles[0][3],
rectangles[0][2] + "," + rectangles[0][3]))) {
return false;
}
return area == (Integer.parseInt(rectangles[0][2] + "," + rectangles[0][3]) - Integer.parseInt(rectangles[0][0] + "," + rectangles[0][1]));
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 391 (Perfect Rectangle)?
This page provides optimized solutions for LeetCode problem 391 (Perfect Rectangle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 391 (Perfect Rectangle)?
The time complexity for LeetCode 391 (Perfect Rectangle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 391 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 391 in Java, C++, or Python.