561/670

561. Minimum Area Rectangle

Medium

Your function receives points, a list of distinct [x, y] grid points. Pick any four of them that form a rectangle whose sides are parallel to the axes — the question is: what is the smallest possible area of such a rectangle?

Return that minimum area, or 0 if no four points form an axis-parallel rectangle at all.

Tilted rectangles do not count here; only ones whose sides run straight along the x- and y-directions.

The smallest axis-parallel rectangleExample 1: the four gold points form a 2×2 rectangle (area 4). The point (2,2) lies inside it but is no corner. Opposite corners (1,1) and (3,3) determine the other two corners completely.
012340123width 2 × height 2area = 4(2,2) is inside,not a corner

Example 1:

Input: points = [[1, 1], [1, 3], [3, 1], [3, 3], [2, 2]]

Output: 4

Explanation: The corners (1,1), (1,3), (3,1) and (3,3) make a 2×2 rectangle of area 4. The point (2,2) sits inside and is not a corner of anything.

Example 2:

Input: points = [[1, 1], [1, 3], [3, 1], [3, 3], [4, 1], [4, 3]]

Output: 2

Explanation: Two rectangles exist: the 2×2 one of area 4, and the 1×2 one on corners (3,1), (3,3), (4,1), (4,3) with area 2. The minimum is 2.

Constraints:

  • 1 ≤ points.length ≤ 500
  • 0 ≤ x, y ≤ 4 * 10⁴
  • All points are distinct.

Hints:

An axis-parallel rectangle is fully determined by two opposite corners (x1, y1) and (x2, y2) with x1 != x2 and y1 != y2 — the other two corners must be (x1, y2) and (x2, y1).

Put every point in a hash set. Then any pair of points can be tested as a diagonal with two O(1) lookups.

Alternatively, group points by x-coordinate. A rectangle is two columns sharing the same pair of y-values — remember, for each y-pair, the last column where you saw it.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: points = [[1, 1], [1, 3], [3, 1], [3, 3], [2, 2]]

Expected output: 4