Minimum Area Rectangle — LeetCode 939 Python Solution
MediumGeometryArrayHash TableMathSorting
- Problem
- #939
- Pattern
- Sorting
- Reading time
- 3 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 a rectangle formed from these points, with sides parallel to the X and Y axes.
Example
- Input
- points = [[1,1],[1,3],[3,1],[3,3],[2,2]]
- Output
- 4
Python solution
Python
class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
d = defaultdict(list)
for x, y in points:
d[x].append(y)
pos = {}
ans = inf
for x in sorted(d):
ys = d[x]
ys.sort()
n = len(ys)
for i, y1 in enumerate(ys):
for y2 in ys[i + 1 :]:
if (y1, y2) in pos:
ans = min(ans, (x - pos[(y1, y2)]) * (y2 - y1))
pos[(y1, y2)] = x
return 0 if ans == inf else ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 939. Minimum Area Rectangle is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 939. Minimum Area Rectangle?
- LeetCode 939. Minimum Area Rectangle is rated Medium on LeetCode.
- What is the time complexity of LeetCode 939. Minimum Area Rectangle?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 939. Minimum Area Rectangle?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 939. Minimum Area Rectangle cover?
- LeetCode 939. Minimum Area Rectangle is tagged Geometry, Array, Hash Table, Math and Sorting on LeetCode.