Taro Logo

Maximum Area Rectangle With Point Constraints II

Hard
Asked by:
Profile picture
3 views
Topics:
ArraysBinary Search

There are n points on an infinite plane. You are given two integer arrays xCoord and yCoord where (xCoord[i], yCoord[i]) represents the coordinates of the ith point.

Your task is to find the maximum area of a rectangle that:

  • Can be formed using four of these points as its corners.
  • Does not contain any other point inside or on its border.
  • Has its edges parallel to the axes.

Return the maximum area that you can obtain or -1 if no such rectangle is possible.

Example 1:

Input: xCoord = [1,1,3,3], yCoord = [1,3,1,3]

Output: 4

Explanation:

Example 1 diagram

We can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border. Hence, the maximum possible area would be 4.

Example 2:

Input: xCoord = [1,1,3,3,2], yCoord = [1,3,1,3,2]

Output: -1

Explanation:

Example 2 diagram

There is only one rectangle possible is with points [1,1], [1,3], [3,1] and [3,3] but [2,2] will always lie inside it. Hence, returning -1.

Example 3:

Input: xCoord = [1,1,3,3,1,3], yCoord = [1,3,1,3,2,2]

Output: 2

Explanation:

Example 3 diagram

The maximum area rectangle is formed by the points [1,3], [1,2], [3,2], [3,3], which has an area of 2. Additionally, the points [1,1], [1,2], [3,1], [3,2] also form a valid rectangle with the same area.

Constraints:

  • 1 <= xCoord.length == yCoord.length <= 2 * 105
  • 0 <= xCoord[i], yCoord[i] <= 8 * 107
  • All the given points are unique.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if no valid rectangle can be formed with the given constraints?
  2. Can the input contain duplicate points, and if so, how should we handle them when forming a rectangle?
  3. What is the exact definition of 'interior and boundaries of the rectangle must not contain any other given points'? Does this mean strictly no other points can lie on the edges or inside the rectangle, or are collinear points on the boundary permitted?
  4. What is the expected range of coordinates for the points, and can they be negative or floating-point numbers?
  5. What is the maximum number of points we can expect in the input set (e.g., up to $10^3$, $10^5$, etc.)?

Brute Force Solution

Approach

Imagine you have a collection of points scattered across a large grid and you want to find the largest possible rectangle that can be formed using four of these points as corners, without any other points trapped inside or on its borders. The brute force strategy involves testing every single group of four points to see if they form a valid rectangle.

Here's how the algorithm would work step-by-step:

  1. Look at the entire collection of points on the grid and pick any four distinct points.
  2. Check if these four chosen points can form a rectangle by making sure their positions line up properly so they create four right angles at the corners.
  3. If they do not form a rectangle, ignore this group and pick a different set of four points.
  4. If they do form a rectangle, examine all the other points in the collection to see if any of them lie strictly inside the rectangle or on its outer edges.
  5. If you find even one other point trapped inside or on the border of this rectangle, discard it because it violates the rules.
  6. If the rectangle is completely empty of other points inside and on its borders, calculate the total area enclosed by the four corner points.
  7. Keep a running note of the largest area you have found so far, updating it whenever you find a valid rectangle that is bigger than the previous record.
  8. Repeat this entire process for every possible combination of four points until you have checked all of them, and then proudly declare the largest area you discovered.

Code Implementation

class Solution:
    def maxRectangleArea(self, points: list[list[int]]) -> int:
        max_area_found = -1
        total_points = len(points)
        
        # Iterate through all combinations of four distinct points to test every possible rectangle
        for first_index in range(total_points):
            for second_index in range(first_index + 1, total_points):
                for third_index in range(second_index + 1, total_points):
                    for fourth_index in range(third_index + 1, total_points):
                        
                        point_one = points[first_index]
                        point_two = points[second_index]
                        point_three = points[third_index]
                        point_four = points[fourth_index]
                        
                        all_points_group = [point_one, point_two, point_three, point_four]
                        sorted_by_x = sorted(all_points_group, key=lambda coord: (coord[0], coord[1]))
                        
                        if sorted_by_x[0][0] == sorted_by_x[1][0] and sorted_by_x[2][0] == sorted_by_x[3][0]:
                            if sorted_by_x[0][1] == sorted_by_x[2][1] and sorted_by_x[1][1] == sorted_by_x[3][1]:
                                min_x = sorted_by_x[0][0]
                                max_x = sorted_by_x[2][0]
                                min_y = sorted_by_x[0][1]
                                max_y = sorted_by_x[1][1]
                                
                                if min_x == max_x or min_y == max_y:
                                    continue
                                
                                point_is_inside = False
                                
                                # Check all remaining points in the grid to ensure no point violates the empty rectangle constraint
                                for check_index in range(total_points):
                                    if check_index in (first_index, second_index, third_index, fourth_index):
                                        continue
                                    
                                    candidate_x, candidate_y = points[check_index]
                                    if min_x <= candidate_x <= max_x and min_y <= candidate_y <= max_y:
                                        point_is_inside = True
                                        break
                                
                                if not point_is_inside:
                                    current_width = max_x - min_x
                                    current_height = max_y - min_y
                                    current_area = current_width * current_height
                                    
                                    # Keep track of the largest valid area found so far among all tested empty rectangles
                                    if current_area > max_area_found:
                                        max_area_found = current_area
                                        
        return max_area_found

Big(O) Analysis

Time Complexity
O(n⁵) – For a collection of n points, choosing every possible combination of four distinct corner points requires checking four nested selections, which takes O(n⁴) combinations. For each chosen quadrilateral, the algorithm must iterate through all n points in the collection to verify if any lie inside or on the border. Multiplying the O(n⁴) combinations by the O(n) scan for interior points yields approximately n * n⁴ operations, which simplifies to O(n⁵).
Space Complexity
O(N) – To implement this algorithm efficiently, we store the coordinates of the N input points in a hash map or a sorted data structure to quickly verify the existence of corner points and check for any points lying inside or on the boundaries of potential rectangles. The auxiliary space is entirely driven by this data structure, which holds all N points along with their positional mappings. As the number of points grows, the memory consumed by these look-up tables scales linearly with the input size N. Therefore, the overall auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

Instead of checking every single possible pair of points to form a rectangle, the optimal approach organizes the points by their vertical and horizontal alignments. It then systematically searches for valid opposite corners while quickly verifying that no forbidden points are trapped inside.

Here's how the algorithm would work step-by-step:

  1. Group all the given points by their vertical positions so we can easily find pairs of points that share the exact same height.
  2. Sort these horizontal pairs from left to right based on their horizontal positions to establish a logical scanning order.
  3. Scan through the organized points to find pairs that share both the same left horizontal coordinate and the same right horizontal coordinate, which gives us the potential width and vertical span of a rectangle.
  4. As we consider these potential rectangles, keep track of the previously seen vertical spans to instantly recognize when two matching horizontal segments can form the top and bottom of a rectangle.
  5. Before celebrating a found rectangle, use a fast range-checking shortcut to ensure that no other point from the overall set lies strictly inside or on the border where it shouldn't be.
  6. Keep a running record of the largest valid area found during the scan, and update it whenever a larger rectangle successfully passes all the safety checks.

Code Implementation

class Solution:
    def max_rectangle_area(self, points: list[list[int]]) -> int:
        from collections import defaultdict
        import bisect

        point_set = set((x_coord, y_coord) for x_coord, y_coord in points)
        vertical_groups = defaultdict(list)
        for x_coord, y_coord in points:
            vertical_groups[x_coord].append(y_coord)

        for x_coord in vertical_groups:
            vertical_groups[x_coord].sort()

        # Grouping by x-coordinate allows us to efficiently find vertical segments.
        sorted_x_coords = sorted(vertical_groups.keys())
        segment_tracker = {}
        maximum_area = -1

        for current_x in sorted_x_coords:
            y_list = vertical_groups[current_x]
            total_y_points = len(y_list)
            for first_index in range(total_y_points):
                for second_index in range(first_index + 1, total_y_points):
                    bottom_y = y_list[first_index]
                    top_y = y_list[second_index]
                    interval_pair = (bottom_y, top_y)

                    # Tracking previous spans lets us instantly identify matching rectangle heights.
                    if interval_pair in segment_tracker:
                        previous_x = segment_tracker[interval_pair]
                        width = current_x - previous_x
                        height = top_y - bottom_y
                        current_area = width * height

                        # Checking interior points ensures no forbidden coordinates violate the rectangle.
                        is_valid_rectangle = True
                        for checked_x in sorted_x_coords:
                            if previous_x < checked_x < current_x:
                                idx_lower = bisect.bisect_left(vertical_groups[checked_x], bottom_y)
                                idx_upper = bisect.bisect_right(vertical_groups[checked_x], top_y)
                                if idx_upper - idx_lower > 0:
                                    is_valid_rectangle = False
                                    break

                        if is_valid_rectangle:
                            for checked_x in [previous_x, current_x]:
                                idx_lower = bisect.bisect_left(vertical_groups[checked_x], bottom_y)
                                idx_upper = bisect.bisect_right(vertical_groups[checked_x], top_y)
                                if idx_upper - idx_lower != 2:
                                    is_valid_rectangle = False
                                    break

                        if is_valid_rectangle:
                            maximum_area = max(maximum_area, current_area)

                    segment_tracker[interval_pair] = current_x

        # Maintaining the max area throughout guarantees we return the optimal solution.
        return maximum_area

Big(O) Analysis

Time Complexity
O(n²) – Grouping and sorting all n points by their coordinates takes O(n log n) time. Scanning through the organized horizontal pairs to evaluate potential rectangles and check for interior points involves examining combinations of point pairs. Across the dataset, this systematic search requires inspecting pairs of horizontal segments, leading to approximately n * n / 2 checks in the worst-case scenario. Simplifying this total operation count yields a final time complexity of O(n²).
Space Complexity
O(N) – The auxiliary space is dominated by the hash maps and lists used to group the points by their vertical and horizontal positions, where N is the total number of input points. Specifically, storing the coordinates in lookup structures and maintaining the history of previously seen vertical spans requires memory proportional to the number of points. As the input size N increases, these internal collections scale linearly to hold the coordinates and valid rectangle boundaries. Therefore, the total extra memory simplifies to O(N) in Big O notation.

Edge Cases

Fewer than 4 points provided in the input set
How to Handle:
Return the specific indicator for no rectangle since at least 4 vertices are required to form a rectangle.
Points forming a rectangle but containing other points strictly inside or on the boundary
How to Handle:
Filter out candidate rectangles by verifying that the bounding box defined by the diagonal points contains zero other points.
Points with negative coordinates or large coordinate values up to 10^9
How to Handle:
Use coordinate compression or hash maps with coordinate pairs to safely index and compare points without out-of-bounds issues.
Duplicate points in the input set
How to Handle:
Deduplicate the input array initially using a set to ensure unique vertex locations and prevent degenerate rectangle checks.
No valid rectangles exist under the point constraints
How to Handle:
Return -1 or the designated sentinel value indicating that no valid empty rectangle could be formed.
Extremely large number of points scaling towards the maximum constraint limit
How to Handle:
Optimize the search by grouping points by x or y coordinates and utilizing sweep-line algorithms or interval trees for efficient range queries.
Large coordinate products resulting in integer overflow when calculating area
How to Handle:
Perform all area calculations using 64-bit integer types to prevent overflow during multiplication of high coordinate differences.
Points forming valid rectangles that share overlapping edges or are nested within each other
How to Handle:
Independently evaluate all valid pairs of diagonal points and only retain the maximum calculated area that satisfies the empty constraint.