MediumNo. 0939
Minimum Area Rectangle — LeetCode 939 Python Solution
- Pattern
- Sorting
- Topics
- Geometry, Array, Hash Table, Math, 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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0963 | Minimum Area Rectangle II | Medium |
| 0149 | Max Points on a Line | Hard |
| 0268 | Missing Number | Easy |
| 0391 | Perfect Rectangle | Hard |
| 0710 | Random Pick with Blacklist | Hard |
| 2249 | Count Lattice Points Inside a Circle | Medium |
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.