Magicsheet logo

Minimum Area Rectangle II

Medium
92.3%
Updated 6/1/2025

Asked by 2 Companies

Minimum Area Rectangle II

What is this problem about?

The Minimum Area Rectangle II is the harder sibling of the previous problem. Here, the rectangle's sides do not have to be parallel to the X and Y axes. You can form a rectangle at any angle. Given a set of points, you must find the minimum area of any valid rectangle.

Why is this asked in interviews?

This Minimum Area Rectangle II interview question is a favorite at Google and Verily for high-level candidates. It tests advanced geometry and the ability to use complex keys in a Hash Map. It requires knowledge of the property that a rectangle's diagonals are equal in length and bisect each other.

Algorithmic pattern used

The Geometry and Hash Map interview pattern used here relies on diagonal properties:

  1. Every pair of points (p1, p2) can be a potential diagonal.
  2. Calculate the length of the diagonal and the midpoint (x_mid, y_mid).
  3. Use a Hash Map where the key is (length, x_mid, y_mid). Store all pairs of points that share the same diagonal properties.
  4. For every pair of diagonals in the same bucket, they form a rectangle. Calculate the area using the distances between the four points.

Example explanation

Imagine four points forming a tilted square.

  1. Diagonal 1: (0,0) to (2,2). Midpoint (1,1), Length squared 8.
  2. Diagonal 2: (0,2) to (2,0). Midpoint (1,1), Length squared 8.
  3. Since they share the same length and midpoint, these four points form a rectangle.
  4. Area = distance(p1, p3) * distance(p1, p4).

Common mistakes candidates make

  • Iterating through triplets: Trying to find three points that form a right angle (O(N3)O(N^3)). This is acceptable but less efficient than the diagonal approach (O(N2)O(N^2)).
  • Precision errors: Using floating point numbers for Map keys. It's better to store the squared length and the midpoint as a scaled integer or a string to maintain precision.
  • Forgetting the "equal diagonal" property: Trying to solve it using complex slope math which is much more prone to errors and edge cases (like vertical lines).

Interview preparation tip

In 2D geometry, look for invariants. For rectangles, the invariant is the diagonal. For circles, it's the center and radius. Using these as keys in a Hash Map is a powerful technique for reducing complexity from O(N4)O(N^4) to O(N2)O(N^2).

Similar Questions