KatInterview

Maximum Area of a Rotated Rectangle

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationmathgeometryhashing

Last updated

Find the largest surface area of any rectangle formed by four vertices chosen from a given set of 2D points.

You are given a list of unique 2D coordinates representing points on a grid plane.

Select four distinct points from the list that form the four corners of a rectangle. Find and return the maximum area among all valid rectangles that can be created this way.

Note that the sides of the rectangle do not need to be parallel to the coordinate axes (they can be rotated). Squares count as valid rectangles. If no four points form a rectangle, return 0.

Constraints

  • 1 <= len(points) <= 200
  • 0 <= points[i][0], points[i][1] <= 40000
  • All points in the input list are distinct.
  • The return value is guaranteed to be an integer.

Examples

Example 1

Input: max_rectangle_area([[1, 2], [2, 1], [1, 0], [0, 1]])

Output: 2

Example 2

Input: max_rectangle_area([[0, 1], [1, 0], [3, 2], [2, 3], [1, 1], [2, 1], [1, 2], [2, 2]])

Output: 4

Example 3

Input: max_rectangle_area([[0, 0], [1, 0], [2, 1], [0, 1]])

Output: 0

Hints

Hint 1

Instead of picking four corners or testing right angles, consider the geometric properties of a rectangle's diagonals.

Hint 2

A quadrilateral is a rectangle if and only if its two diagonals share the same midpoint and have the exact same length.

Hint 3

To keep everything in integer arithmetic, store double the midpoint `(x1 + x2, y1 + y2)` and the squared diagonal length `(x1 - x2)^2 + (y1 - y2)^2` as a hash key.