LeetCode 0939. Minimum Area Rectangle Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0939. Minimum Area Rectangle

Description

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. If there is not any such rectangle, return 0.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= points.length <= 500
  • points[i].length == 2
  • 0 <= xi, yi <= 4 * 104
  • All the given points are unique.

Solutions

Solution 1

PythonJavaC++Go
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 ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !