Problem Description
Given an array of unique points in the X-Y plane, the task is to determine the minimum area of any rectangle that can be formed using these points as vertices. The rectangle may be rotated, i.e. its sides are not required to be parallel to the X or Y axes. If no rectangle can be formed, return 0. Answers within 10⁻⁵ of the actual value are accepted.
Key Insights
- A rectangle, even when rotated, has the property that its diagonals have the same midpoint and equal lengths.
- By iterating over every pair of points (which can be potential diagonal endpoints), we can group pairs by their midpoint (represented in a way to avoid floating point issues) and their squared distance.
- For each group of pairs sharing the same center and squared distance, any two pairs can potentially form a rectangle.
- Given two candidate diagonal pairs (p, q) and (r, s) with the same midpoint, the rectangle’s area can be computed by taking one vertex p and calculating:
• side1 = distance from p to r
• side2 = distance from p to s
• area = side1 * side2, provided that the vectors (r - p) and (s - p) are perpendicular (i.e. their dot product is zero). - Iterate through all valid pair combinations and keep track of the minimum area found.
Space and Time Complexity
Time Complexity: O(n² * k²) where n is the number of points and k is the number of pairs in each grouping (in worst-case, overall it is O(n⁴), but since n ≤ 50, it is acceptable). Space Complexity: O(n²) for storing all pairs in the dictionary.
Solution
The solution involves:
- Iterating over all pairs of points and computing a key based on the pair’s midpoint (using the sum of coordinates to avoid floating point precision issues) and their squared distance.
- Storing these pairs in a hash map (dictionary) keyed by (center, squared distance).
- For each list in the dictionary with more than one pair, checking every combination of two pairs:
- Choose one endpoint from the first pair and check with both endpoints of the second pair to form two vectors.
- Verify that these two vectors are perpendicular (dot product equals 0). This confirms the points form a rectangle.
- Compute the area of the rectangle as the product of the lengths of the two vectors.
- Return the minimum area among all valid rectangles, or 0 if none exist.
Below are code solutions in multiple languages with detailed line-by-line comments.