Problem 963

Abstract / Summary

Given a set of points find the smallest area of any rectangle whose corners are all in the set

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0963.py

class Solution:
    def minAreaFreeRect(self, points: List[List[int]]) -> float:
        result = +inf

        points.sort()
        all = set([ ( x, y ) for x, y in points ])

        for i, (x1, y1) in enumerate(points):
            for j, (x2, y2) in enumerate(points[i + 1 : ], i + 1):
                # side a
                dx1 = x2 - x1
                dy1 = y2 - y1
                if max(dx1, dy1) >= result: # early exit
                    continue

                for x3, y3 in points[j + 1 : ]:
                    # side b
                    dx2 = x3 - x2
                    dy2 = y3 - y2
                    if max(dx2, dy2) >= result: # early exit
                        continue

                    # dot product is zero iff right angle
                    if dx1 * dx2 + dy1 * dy2 == 0:
                        # conclude fourth point
                        x4 = x3 - dx1
                        y4 = y3 - dy1
                        if ( x4, y4 ) in all:
                            # sqrt(a) * sqrt(b) = sqrt(a * b)
                            a = dx1 * dx1 + dy1 * dy1
                            b = dx2 * dx2 + dy2 * dy2
                            result = min(result, a * b) # defer final sqrt

        return 0 if result == +inf else sqrt(result)
34 lines | 1315 bytes | submitted May 10, 2024 | GitHub   33% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (60k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Geometry
  • Hash Table
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation searches a set of planar points for the rectangle with the smallest possible area whose vertices are all present in the input. It returns the area as a floating-point number, or zero when no rectangle can be formed. The algorithm relies on geometric properties of right-angled quadrilaterals and uses several early-exit checks to prune the search space.

Preparation of Data Structures

The first actions order the points and create a hash-based container for constant-time membership tests.

points.sort()
all = set((x, y) for x, y in points)

Sorting guarantees a deterministic iteration order, which simplifies the nested loops that follow. The set all enables O(1) verification of whether a candidate fourth vertex exists.

Enumerating Candidate Edges

The outer two loops pick an ordered pair of points that could serve as one side of a rectangle. The vector between them is stored as (dx1, dy1).

for i, (x1, y1) in enumerate(points):
    for j, (x2, y2) in enumerate(points[i + 1:], i + 1):
        dx1 = x2 - x1
        dy1 = y2 - y1
        if max(dx1, dy1) >= result:
            continue

The condition max(dx1, dy1) >= result acts as an early exit: if the length of the current side already exceeds the best area found (stored as the product of side lengths), any rectangle built from this side cannot improve the result, so the iteration skips further work.

Adding a Third Vertex to Form a Right Angle

A third point is examined to create a second side that meets the first at a right angle. The vector from the second to the third point is (dx2, dy2).

for x3, y3 in points[j + 1:]:
    dx2 = x3 - x2
    dy2 = y3 - y2
    if max(dx2, dy2) >= result:
        continue
    if dx1 * dx2 + dy1 * dy2 == 0:
        ...

The dot-product test dx1 * dx2 + dy1 * dy2 == 0 confirms orthogonality, guaranteeing that the three points can be three consecutive vertices of a rectangle.

Determining the Fourth Vertex and Updating the Minimum

When a right angle is detected, the algorithm computes the location of the missing corner by translating the third point back along the first side’s vector. It then checks whether this computed point exists in the original set.

x4 = x3 - dx1
y4 = y3 - dy1
if (x4, y4) in all:
    a = dx1 * dx1 + dy1 * dy1
    b = dx2 * dx2 + dy2 * dy2
    result = min(result, a * b)

The squared lengths a and b avoid premature square-root operations. By storing the product a * b, the algorithm defers the final square root until the very end, reducing the number of expensive floating-point calls.

Handling the Absence of a Valid Rectangle

If the search never updates result, it remains at positive infinity. The return statement converts this sentinel into a zero area, indicating that no rectangle could be formed.

return 0 if result == +inf else sqrt(result)

This edge case ensures the function’s output is well-defined for inputs lacking any four-point rectangle.

Performance Optimizations Observed

The code incorporates several techniques that improve runtime efficiency. Sorting the points once enables the use of index-based slicing, which naturally avoids revisiting earlier combinations. The set all provides constant-time containment checks for the hypothesized fourth corner. Early-exit conditions based on the current best area prune large portions of the search space before the costly dot-product or set-lookup steps. Finally, postponing the square root until after the minimum area is identified reduces the number of floating-point operations, especially when many candidate rectangles are examined.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bucket filled with shiny little dots scattered all over a piece of paper. This code is looking for the smallest rectangle you can build by connecting four of those dots.

First, the code organizes the dots so they are easier to look at. Then, it starts picking three dots at a time to see if they can form three corners of a rectangle. It checks the distance between the first two dots and the distance between the second and third dots to see if they make a perfect square corner like the ones on a book or a table.

When it finds that special square corner, it uses math to figure out exactly where a fourth dot would need to be to finish the shape. It checks if there is already a dot in the bucket at that perfect spot. If there is, it measures how big the rectangle would be and keeps track if this one is the smallest one found so far. It keeps doing this until it has checked every possible shape it can build, always keeping the tiniest one in its pocket.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.65 | σ = 1.57

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
suxrobGM C#
wisdompeak C++
24 links | 11 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   May 10, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality