LeetCode 1459: Rectangles Area Solution

Master LeetCode problem 1459 (Rectangles Area), a medium 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.

1459. Rectangles Area

Medium

Problem Explanation

Explanation:

To solve this problem, we need to find the total area covered by a set of rectangles. We can do this by first creating a list of all the x-coordinates where the rectangles start or end, sorted in ascending order. Then, we iterate through these x-coordinates and calculate the total area covered by rectangles at each segment.

  1. Create a list of x-coordinates:

    • Add the x-coordinates of the left and right edges of each rectangle to a list.
    • Sort the list in ascending order to get a sorted list of x-coordinates.
  2. Iterate through the sorted x-coordinates:

    • At each segment between two x-coordinates, calculate the total height covered by rectangles.
    • Multiply the segment width by the total height to get the area covered by rectangles in that segment.
    • Update the total area by adding the area of the current segment.
  3. Return the total area as the final result.

Time Complexity: O(nlogn)
Space Complexity: O(n)

: :

Solution Code

import java.util.*;

class Solution {
    public int rectanglesArea(int[][] rectangles) {
        List<Integer> xCoordinates = new ArrayList<>();
        for (int[] rect : rectangles) {
            xCoordinates.add(rect[0]);
            xCoordinates.add(rect[2]);
        }
        Collections.sort(xCoordinates);

        long totalArea = 0;
        for (int i = 0; i < xCoordinates.size() - 1; i++) {
            int start = xCoordinates.get(i);
            int end = xCoordinates.get(i + 1);
            int height = 0;
            for (int[] rect : rectangles) {
                if (rect[0] <= start && rect[2] >= end) {
                    height = Math.max(height, rect[1]);
                }
            }
            totalArea += (long) (end - start) * height;
        }

        return (int) (totalArea % 1000000007);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1459 (Rectangles Area)?

This page provides optimized solutions for LeetCode problem 1459 (Rectangles Area) 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 1459 (Rectangles Area)?

The time complexity for LeetCode 1459 (Rectangles Area) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1459 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1459 in Java, C++, or Python.

Back to LeetCode Solutions