Taro Logo

Maximum Area Rectangle With Point Constraints I

#1 Most AskedMedium
2 views
Topics:
Arrays

You are given an array points where points[i] = [xi, yi] represents the coordinates of a point on an infinite plane.

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: points = [[1,1],[1,3],[3,1],[3,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: points = [[1,1],[1,3],[3,1],[3,3],[2,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: points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,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 <= points.length <= 10
  • points[i].length == 2
  • 0 <= xi, yi <= 100
  • 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. Can the input points contain duplicate coordinates, and if so, how should we handle them when forming a rectangle?
  2. Does 'strictly inside or on the boundary' mean that if another point lies anywhere on the perimeter lines (edges) of the rectangle, the rectangle is considered invalid?
  3. What is the expected return value if no valid rectangle can be formed with the given constraints?
  4. What is the maximum number of points we can expect in the input array?
  5. Can the coordinates be negative numbers, and is there any specific range or limit on the coordinate values?

Brute Force Solution

Approach

Imagine you have a scatter of dots on a giant sheet of paper and you want to find the biggest rectangle you can draw using some of these dots as corners. The brute force approach checks every possible combination of four dots to see if they form a valid rectangle, and if so, how big it is.

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

  1. Look at every possible group of four distinct dots on the paper.
  2. Check if these four dots form a rectangle where the sides are completely vertical and horizontal.
  3. If they do form a valid rectangle, check the inside and the edges to make sure no other dots are touching or trapped inside this rectangle.
  4. If the rectangle is completely clear of any other dots, calculate its total area by multiplying its width by its height.
  5. Keep track of the largest area you have found so far.
  6. Repeat this process for every other possible group of four dots.
  7. At the very end, report the largest area you discovered, or state that no valid rectangles were found if none worked out.

Code Implementation

def max_rectangle_area(point_list):    maximum_area_found = -1    total_points = len(point_list)    # We iterate through every combination of four distinct points to evaluate potential rectangles    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 = point_list[first_index]                    point_two = point_list[second_index]                    point_three = point_list[third_index]                    point_four = point_list[fourth_index]                    four_points = [point_one, point_two, point_three, point_four]                    four_points.sort(key=lambda coord: (coord[0], coord[1]))                    p1, p2, p3, p4 = four_points[0], four_points[1], four_points[2], four_points[3]                    if p1[0] == p2[0] and p3[0] == p4[0] and p1[1] == p3[1] and p2[1] == p4[1] and p1[0] < p3[0] and p1[1] < p2[1]:                        current_width = p3[0] - p1[0]                        current_height = p2[1] - p1[1]                        current_area = current_width * current_height                        is_rectangle_empty = True                        # We check all other points to ensure no conflicting points lie inside or on the boundaries                        for check_index in range(total_points):                            if check_index in (first_index, second_index, third_index, fourth_index):                                continue                            other_point = point_list[check_index]                            if p1[0] <= other_point[0] <= p3[0] and p1[1] <= other_point[1] <= p2[1]:                                is_rectangle_empty = False                                break                        if is_rectangle_empty:                            if current_area > maximum_area_found:                                maximum_area_found = current_area    # We return the largest clear rectangle area found, defaulting to negative one if none exist    return maximum_area_found

Big(O) Analysis

Time Complexity
O(n^5) – For an input of n points, we first iterate through every possible combination of four distinct points to define the rectangle corners, taking O(n^4) time. For each chosen group of four points, we must then iterate through all n points in the dataset to check if any other point lies strictly inside or on the edges of the rectangle. This nested validation adds an extra factor of n to each of the approximately n^4/24 combinations. Consequently, the total operations scale roughly as n^5, which simplifies to a Big O time complexity of O(n^5).
Space Complexity
O(n) – To solve this problem efficiently, we store the coordinates of all dots in a hash set to allow O(1) lookups during the point-constraint validation. Assuming N is the number of given dots, this hash set requires auxiliary memory proportional to the number of elements stored. Consequently, the extra space required scales linearly with the input size N, resulting in an overall auxiliary space complexity of O(n).

Optimal Solution

Approach

To find the largest possible rectangle formed by specific points, the optimal strategy is to systematically test pairs of points that could serve opposite corners of a rectangle. For each chosen pair, it quickly checks if there are any forbidden points trapped inside or on the edges that would ruin the shape.

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

  1. Imagine plotting all the given points on a giant grid.
  2. Pick every possible pair of points, treating them as opposite corners that define the diagonal of a potential rectangle.
  3. Check if these two points can actually form a valid rectangle where one is the bottom-left and the other is the top-right.
  4. If they form a valid rectangle, inspect all the other given points to make sure no other point falls strictly inside this rectangle or on its borders.
  5. If the rectangle is completely empty of other points except for its four proper corners, calculate its total area.
  6. Keep track of the largest area found so far and update it whenever a bigger valid rectangle is discovered.
  7. After checking all possible pairs, declare the largest recorded area as your final answer.

Code Implementation

class Solution:
    def max_rectangle_area(self, point_collection: list[list[int]]) -> int:
        maximum_area_found = -1
        point_set = set(tuple(coordinate) for coordinate in point_collection)
        
        # Iterate through every possible pair of points to evaluate as potential diagonal corners.
        for point_index_i in range(len(point_collection)):
            for point_index_j in range(point_index_i + 1, len(point_collection)):
                bottom_left_x, bottom_left_y = point_collection[point_index_i]
                top_right_x, top_right_y = point_collection[point_index_j]
                
                if bottom_left_x >= top_right_x or bottom_left_y >= top_right_y:
                    continue
                
                if (bottom_left_x, top_right_y) not in point_set or (top_right_x, bottom_left_y) not in point_set:
                    continue
                
                contains_other_points = False
                
                # Verify that no other points reside strictly inside or on the boundaries of this rectangle.
                for candidate_point in point_collection:
                    candidate_x, candidate_y = candidate_point
                    if bottom_left_x <= candidate_x <= top_right_x and bottom_left_y <= candidate_y <= top_right_y:
                        if candidate_point != [bottom_left_x, bottom_left_y] and candidate_point != [top_right_x, top_right_y] and candidate_point != [bottom_left_x, top_right_y] and candidate_point != [top_right_x, bottom_left_y]:
                            contains_other_points = True
                            break
                
                if not contains_other_points:
                    current_area = (top_right_x - bottom_left_x) * (top_right_y - bottom_left_y)
                    maximum_area_found = max(maximum_area_found, current_area)
        
        # Return the largest valid rectangle area discovered, or negative one if none exist.
        return maximum_area_found

Big(O) Analysis

Time Complexity
O(n^3) – Let n be the number of given points on the grid. We iterate through every possible pair of points to serve as opposite corners, requiring n squared pairs. For each pair that forms a valid diagonal, we then iterate through all n points to check if any are trapped inside or on the borders. This results in approximately n squared pairs multiplied by n points, which totals n cubed operations and simplifies to O(n^3).
Space Complexity
O(N) – To analyze the auxiliary space, let N be the total number of points given in the input grid. The algorithm stores all N points in a coordinate lookup structure or hash set to quickly check for the existence of corner points and forbidden points during the validation steps. Additionally, the iteration variables and the running maximum area variable require a constant amount of extra memory. Therefore, the dominant factor determining the extra memory is the storage of the N points in our lookup structures. Simplifying this memory consumption to Big O notation yields O(N).

Edge Cases

Fewer than 4 points provided in the input array
How to Handle:
Return -1 immediately as at least 4 corners are required to form any rectangle.
Points with duplicate coordinates
How to Handle:
Filter out duplicate points or use a set data structure during preprocessing to avoid redundant checks and incorrect inclusion validation.
Points containing negative coordinates and large extreme values
How to Handle:
Use standard integer types with coordinate comparisons that correctly handle negative ranges and prevent coordinate-based underflow.
No valid rectangle can be formed due to interior or boundary point constraints
How to Handle:
Iterate through all valid pairs of diagonal points, verify the absence of other points inside or on the boundary, and return -1 if none pass.
Collinear points forming zero-area degenerate rectangles
How to Handle:
Ensure rectangle width and height calculations strictly enforce positive non-zero dimensions before computing area.
Points forming valid rectangles that contain other points strictly inside or on their boundaries
How to Handle:
Perform a secondary validation pass over all given points to ensure no other point falls inclusively within the bounding box of the candidate rectangle.
Large input scale leading to time limit exceeded due to O(N^3) or worse complexity
How to Handle:
Optimize the search by hashing point coordinates for O(1) lookup and iterating intelligently over potential diagonal pairs.
Integer overflow during area calculation with very large coordinates
How to Handle:
Use 64-bit integers to store and compare products of coordinate differences to prevent arithmetic overflow.
0/11 completed