Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Area Rectangle solution and explanation

MediumArrayGeometryHash TableMath5 min read55.4% acceptanceUpdated 9 Apr 2026
MINIMUM AREA RECTANGLE | GOOGLE INTERVIEW QUESTION | PYTHON SOLUTIONCracking FAANG · 14:16 · 18K viewsWatch on YouTube
9 more videos on this problem
  1. MINIMUM AREA RECTANGLE | GOOGLE INTERVIEW QUESTION | PYTHON SOLUTIONCracking FAANG · 14:16 · 18K views
  2. Leetcode | 939. Minimum Area Rectangle(Explained)Sonu Raj · 8:52 · 7K views
  3. LeetCode 939. Minimum Area RectangleHappy Coding · 36:33 · 4K views
  4. LeetCode 939 Minimum Area Rectangle - Simple Solution (Logic Explained With Examples)AlgorithmicIQ · 15:55 · 2K views
  5. 【每日一题】939. Minimum Area Rectangle, 07/04/2019Huifeng Guan · 23:17 · 1K views
  6. Leetcode 939 | Minimum Area RectangleRoad To FAANG · 10:38 · 999 views
  7. 939. Minimum Area Rectangle | English | MediumSimple Code - 단순코드 · 6:48 · 989 views
  8. 939. Minimum Area Rectangle (Leetcode Medium)Programming Live with Larry · 12:17 · 674 views
  9. 小旭讲解 LeetCode 939. Minimum Area Rectangle - EP26HU Xiaoxu · 10:53 · 380 views
  10. LeetCode - 939. Minimum Area Rectangle | JavaOrkhan Gasanov · 14:24 · 272 views

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. 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.

Approach overview

Problem Overview: You receive a list of 2D points on a grid. Four of those points can form an axis-aligned rectangle if they share two distinct x-coordinates and two distinct y-coordinates. The goal is to compute the smallest possible rectangle area formed by any four points. If no rectangle exists, return 0.

Approach 1: Using Dynamic Programming (O(n^2) time, O(n^2) space)

Group points by their x coordinate so each column contains the y values that appear at that x-position. Sort the y values within each column. For every pair of (y1, y2) in the same column, treat it as a potential vertical edge of a rectangle. Maintain a DP structure dp[y1][y2] that stores the last x coordinate where this pair appeared. When the same pair appears in a new column, you have two vertical edges. The rectangle area becomes (x - dp[y1][y2]) * (y2 - y1). Update the minimum area and refresh the stored column.

This works because a rectangle is uniquely determined by two vertical edges with identical y pairs. The DP table remembers where each vertical edge pair previously occurred, allowing constant-time area calculation when the pair reappears. The approach relies heavily on fast lookups using a structure similar to a hash table while iterating through sorted columns of points.

Approach 2: Optimizing Space using Two Variables (O(n^2) time, O(n) space)

The full DP table can grow large if many unique y values exist. Instead of storing a dense 2D matrix for dp[y1][y2], track pairs using a compact key such as (y1, y2) in a hash map. For each column, iterate through all combinations of two y values. The map stores the last column where that pair appeared. When encountered again, compute the area using the previous column and update the minimum rectangle.

This optimization removes the need for a large DP matrix while preserving the same logic. Each pair is processed using constant-time hash lookups. The algorithm still scans all vertical pairs in each column, so the time complexity remains O(n^2), but memory drops significantly because only observed pairs are stored. The approach fits well for sparse coordinate distributions often seen in geometry problems.

Recommended for interviews: Interviewers typically expect the hash-based pair tracking approach (Approach 2). A brute-force rectangle check over all point quadruples shows basic understanding but is too slow. Demonstrating the vertical edge insight and storing (y1, y2) pairs in a array/hash structure shows strong problem-solving and familiarity with geometric pattern recognition.

Approach 1: Approach 1: Using Dynamic Programming

This approach involves using dynamic programming to efficiently solve the problem by breaking it down into overlapping subproblems. The solution stores the results of subproblems to avoid unnecessary recalculations, making it more efficient.

def solve(arr):
    if not arr:
        return 0
    if len(arr) == 1:
        return arr[0]

    dp = [0] * len(arr)
    dp[0] = arr[0]
    dp[1] = max(arr[0], arr[1])

    for i in range(2, len(arr)):
        dp[i] = max(arr[i] + dp[i-2], dp[i-1])
    
    return dp[-1]

arr = [3, 2, 7, 10]
print("Maximum sum:", solve(arr))
public class Solution {
    public static int solve(int[] arr) {
        int n = arr.length;
        if (n == 0) return 0;
        if (n == 1) return arr[0];

        int[] dp = new int[n];
        dp[0] = arr[0];
        dp[1] = Math.max(arr[0], arr[1]);

        for (int i = 2; i < n; i++) {
            dp[i] = Math.max(arr[i] + dp[i-2], dp[i-1]);
        }
        return dp[n-1];
    }

    public static void main(String[] args) {
        int[] arr = {3, 2, 7, 10};
        System.out.println("Maximum sum: " + solve(arr));
    }
}
#include <iostream>
#include <vector>

int solve(const std::vector<int>& arr) {
    int n = arr.size();
    if (n == 0) return 0;
    if (n == 1) return arr[0];

    std::vector<int> dp(n);
    dp[0] = arr[0];
    dp[1] = std::max(arr[0], arr[1]);

    for (int i = 2; i < n; ++i) {
        dp[i] = std::max(arr[i] + dp[i-2], dp[i-1]);
    }
    return dp[n-1];
}

int main() {
    std::vector<int> arr = {3, 2, 7, 10};
    std::cout << "Maximum sum: " << solve(arr) << std::endl;
    return 0;
}
function solve(arr) {
    if (arr.length === 0) return 0;
    if (arr.length === 1) return arr[0];

    let dp = [arr[0], Math.max(arr[0], arr[1])];

    for (let i = 2; i < arr.length; i++) {
        dp[i] = Math.max(arr[i] + dp[i-2], dp[i-1]);
    }
    return dp[arr.length - 1];
}

const arr = [3, 2, 7, 10];
console.log("Maximum sum:", solve(arr));
#include <stdio.h>

int solve(int arr[], int n) {
    int dp[n];
    dp[0] = arr[0];
    
    for (int i = 1; i < n; i++) {
        dp[i] = arr[i];
        if (i > 1)
            dp[i] += dp[i-2];
        if (dp[i] < dp[i-1])
            dp[i] = dp[i-1];
    }
    return dp[n-1];
}

int main() {
    int arr[] = {3, 2, 7, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Maximum sum: %d\n", solve(arr, n));
    return 0;
}
using System;

class Solution {
    public static int Solve(int[] arr) {
        int n = arr.Length;
        if (n == 0) return 0;
        if (n == 1) return arr[0];

        int[] dp = new int[n];
        dp[0] = arr[0];
        dp[1] = Math.Max(arr[0], arr[1]);

        for (int i = 2; i < n; i++) {
            dp[i] = Math.Max(arr[i] + dp[i-2], dp[i-1]);
        }
        return dp[n-1];
    }

    static void Main() {
        int[] arr = {3, 2, 7, 10};
        Console.WriteLine("Maximum sum: " + Solve(arr));
    }
}

This Python solution uses a list to sequentially compute the maximum sum possible by using a dynamic programming approach, which involves deciding at each step whether to include or exclude the current value.

Complexity

Time Complexity: O(n)
Space Complexity: O(n)

Try this approach in the editor

Approach 2: Approach 2: Optimizing Space using Two Variables

This approach is a refinement of the dynamic programming method, designed to use less space. Instead of maintaining an entire array to keep track of intermediate results, we only keep two variables to store the most recent results.

def solve(arr):
    if not arr:
        return 0
    if len(arr) == 1:
        return arr[0]

    prev1, prev2 = arr[0], 0
    for num in arr[1:]:
        prev1, prev2 = max(prev2 + num, prev1), prev1
    
    return prev1

arr = [3, 2, 7, 10]
print("Maximum sum:", solve(arr))
public class Solution {
    public static int solve(int[] arr) {
        if (arr.length == 0) return 0;
        if (arr.length == 1) return arr[0];

        int prev1 = arr[0], prev2 = 0;
        for (int i = 1; i < arr.length; i++) {
            int temp = prev1;
            prev1 = Math.max(prev2 + arr[i], prev1);
            prev2 = temp;
        }
        return prev1;
    }

    public static void main(String[] args) {
        int[] arr = {3, 2, 7, 10};
        System.out.println("Maximum sum: " + solve(arr));
    }
}
#include <iostream>
#include <vector>

int solve(const std::vector<int>& arr) {
    if (arr.empty()) return 0;
    if (arr.size() == 1) return arr[0];

    int prev1 = arr[0], prev2 = 0;
    for (size_t i = 1; i < arr.size(); ++i) {
        int temp = prev1;
        prev1 = std::max(prev2 + arr[i], prev1);
        prev2 = temp;
    }
    return prev1;
}

int main() {
    std::vector<int> arr = {3, 2, 7, 10};
    std::cout << "Maximum sum: " << solve(arr) << std::endl;
    return 0;
}
function solve(arr) {
    if (arr.length === 0) return 0;
    if (arr.length === 1) return arr[0];

    let prev1 = arr[0];
    let prev2 = 0;

    for (let i = 1; i < arr.length; i++) {
        const temp = prev1;
        prev1 = Math.max(prev2 + arr[i], prev1);
        prev2 = temp;
    }
    return prev1;
}

const arr = [3, 2, 7, 10];
console.log("Maximum sum:", solve(arr));
#include <stdio.h>

int solve(int arr[], int n) {
    if (n == 0) return 0;
    if (n == 1) return arr[0];

    int prev1 = arr[0], prev2 = 0;
    for (int i = 1; i < n; i++) {
        int temp = prev1;
        prev1 = (prev2 + arr[i] > prev1) ? prev2 + arr[i] : prev1;
        prev2 = temp;
    }
    return prev1;
}

int main() {
    int arr[] = {3, 2, 7, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Maximum sum: %d\n", solve(arr, n));
    return 0;
}
using System;

class Solution {
    public static int Solve(int[] arr) {
        if (arr.Length == 0) return 0;
        if (arr.Length == 1) return arr[0];

        int prev1 = arr[0], prev2 = 0;
        for (int i = 1; i < arr.Length; i++) {
            int temp = prev1;
            prev1 = Math.Max(prev2 + arr[i], prev1);
            prev2 = temp;
        }
        return prev1;
    }

    static void Main() {
        int[] arr = {3, 2, 7, 10};
        Console.WriteLine("Maximum sum: " + Solve(arr));
    }
}

By limiting the space usage to only two variables, this Python solution efficiently calculates the maximum sum while retaining the same performance characteristics as a typical dynamic programming solution.

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Try this approach in the editor

Approach 3: Default Approach

func minAreaRect(points [][]int) int {
	d := map[int][]int{}
	xs := []int{}
	for _, p := range points {
		x, y := p[0], p[1]
		d[x] = append(d[x], y)
	}
	for x := range d {
		xs = append(xs, x)
	}
	sort.Ints(xs)
	type pair struct{ x, y int }
	pos := map[pair]int{}
	ans := 1 << 30
	for _, x := range xs {
		ys := d[x]
		sort.Ints(ys)
		for i, y1 := range ys {
			for _, y2 := range ys[i+1:] {
				p := pair{y1, y2}
				if x1, ok := pos[p]; ok {
					ans = min(ans, (x-x1)*(y2-y1))
				}
				pos[p] = x
			}
		}
	}
	if ans == 1<<30 {
		return 0
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Using Dynamic Programming

Time Complexity: O(n)
Space Complexity: O(n)

Approach 2: Optimizing Space using Two Variables

Time Complexity: O(n)
Space Complexity: O(1)

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Dynamic Programming with 2D Pair TableO(n^2)O(n^2)Useful for understanding the rectangle detection idea with explicit state tracking for every (y1, y2) pair.
Hash Map Pair Tracking (Space Optimized)O(n^2)O(n)Preferred solution in interviews and production when the number of unique y-pairs is sparse.

Frequently asked questions

Is Minimum Area Rectangle easy or hard?

Minimum Area Rectangle is typically classified as a Medium difficulty problem. The challenge lies in recognizing that rectangles can be detected by matching vertical edge pairs across columns rather than checking every combination of four points.

How to solve Minimum Area Rectangle in O(n^2)?

Group points by their x-coordinate, then sort the y-values within each column. For every pair (y1, y2), store the last x-coordinate where this pair appeared in a hash map. When the pair appears again, compute the rectangle area using the difference in x and y coordinates and update the minimum area.

What is the best approach for Minimum Area Rectangle?

The best approach groups points by x-coordinate and tracks vertical edge pairs (y1, y2) using a hash map. When the same pair appears in another column, it forms a rectangle and the area can be computed instantly. This method runs in O(n^2) time with roughly O(n) space and avoids checking every quadruple of points.

What data structure is used in Minimum Area Rectangle?

The core data structure is a hash map that stores pairs of y-coordinates as keys and the last x-coordinate where the pair appeared as the value. Arrays or lists are used to group points by column, and sorting helps process y-pairs in order.

What is the time complexity of Minimum Area Rectangle?

The optimal solution runs in O(n^2) time. For each column, the algorithm checks all pairs of y-values and uses a hash lookup to see if that pair appeared in a previous column. Space complexity is typically O(n) when using a hash map to store previously seen pairs.

Minimum Area Rectangle Python or Java solution approach?

Both Python and Java implementations follow the same strategy: group points by x-coordinate, generate y-pairs for each column, and store them in a hash map. When a pair reappears in a new column, calculate the rectangle area and update the minimum. The complexity remains O(n^2).

Is Minimum Area Rectangle asked at Google, Amazon, or Meta?

Minimum Area Rectangle is a common geometry and hash map interview problem and has appeared in interviews at companies such as Google, Amazon, and Meta. It tests the ability to recognize geometric patterns and optimize brute-force rectangle detection using hash-based lookups.

Comments

Now write it yourselfClose this page and solve Minimum Area Rectangle in the editor, without looking.
Practise Minimum Area Rectangle