Minimum Area Rectangle II — LeetCode 963 Python Solution
- Problem
- #963
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given an array of points in the X-Y plane points where points[i] = [xi, yi]. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes.
Example
- Input
- points = [[1,2],[2,1],[1,0],[0,1]]
- Output
- 2.00000
- Explanation
- The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.
Python solution
class Solution:
def minAreaFreeRect(self, points: List[List[int]]) -> float:
s = {(x, y) for x, y in points}
n = len(points)
ans = inf
for i in range(n):
x1, y1 = points[i]
for j in range(n):
if j != i:
x2, y2 = points[j]
for k in range(j + 1, n):
if k != i:
x3, y3 = points[k]
x4 = x2 - x1 + x3
y4 = y2 - y1 + y3
if (x4, y4) in s:
v21 = (x2 - x1, y2 - y1)
v31 = (x3 - x1, y3 - y1)
if v21[0] * v31[0] + v21[1] * v31[1] == 0:
w = sqrt(v21[0] ** 2 + v21[1] ** 2)
h = sqrt(v31[0] ** 2 + v31[1] ** 2)
ans = min(ans, w * h)
return 0 if ans == inf else ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^3) |
| Space | O(n), where n is the length of the array \textit{points} auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 963. Minimum Area Rectangle II is filed here because LeetCode tags it Math and Geometry, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 963. Minimum Area Rectangle II?
- LeetCode 963. Minimum Area Rectangle II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 963. Minimum Area Rectangle II?
- The Python solution on this page runs in O(n^3).
- What is the space complexity of LeetCode 963. Minimum Area Rectangle II?
- The Python solution on this page uses O(n), where n is the length of the array \textit{points} auxiliary space.
- What topics does LeetCode 963. Minimum Area Rectangle II cover?
- LeetCode 963. Minimum Area Rectangle II is tagged Geometry, Array, Hash Table and Math on LeetCode.