LeetCode 939: Minimum Area Rectangle Solution

Master LeetCode problem 939 (Minimum Area Rectangle), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

939. Minimum Area Rectangle

Problem Explanation

Explanation

To find the minimum area rectangle formed by points, we can use a set to store all the points and iterate through all pairs of points to check if a rectangle can be formed using these points. For each pair of points (p1, p2), we can check if the other two points required to form a rectangle are present. If they are, we calculate the area and update the minimum area found so far.

Algorithm:

  1. Iterate over all pairs of points (p1, p2).
  2. Calculate the other two points required to form a rectangle with p1 and p2.
  3. Check if these two points are present in the set of points.
  4. If both points are present, calculate the area of the rectangle and update the minimum area found so far.
  5. Return the minimum area found.

Time Complexity: O(n^2) where n is the number of points. Space Complexity: O(n) to store the points in a set.

Solution Code

class Solution {
    public int minAreaRect(int[][] points) {
        Set<Integer> pointSet = new HashSet<>();
        for (int[] point : points) {
            pointSet.add(40001 * point[0] + point[1]);
        }
        
        int minArea = Integer.MAX_VALUE;
        
        for (int i = 0; i < points.length; i++) {
            for (int j = i + 1; j < points.length; j++) {
                if (points[i][0] != points[j][0] && points[i][1] != points[j][1]) {
                    if (pointSet.contains(40001 * points[i][0] + points[j][1]) &&
                        pointSet.contains(40001 * points[j][0] + points[i][1])) {
                        minArea = Math.min(minArea, Math.abs(points[i][0] - points[j][0]) * Math.abs(points[i][1] - points[j][1]));
                    }
                }
            }
        }
        
        return minArea == Integer.MAX_VALUE ? 0 : minArea;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 939 (Minimum Area Rectangle)?

This page provides optimized solutions for LeetCode problem 939 (Minimum Area Rectangle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 939 (Minimum Area Rectangle)?

The time complexity for LeetCode 939 (Minimum Area Rectangle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 939 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 939 in Java, C++, or Python.

Back to LeetCode Solutions