Last active
November 16, 2021 17:06
-
-
Save denk0403/d57ade8efc6966ba1484d604f3c9ab8a to your computer and use it in GitHub Desktop.
An O(n^2) algorithm for determining the largest area of a rectangle that can be made from a given list of points
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Point = [number, number]; | |
/** | |
* Determines the largest area of a rectangle that can be made from a given list of points. | |
* Rectangles are assumed to be aligned with the axes (no rotations). | |
* Runtime: O(n^2) | |
*/ | |
function largestRectArea(points: Point[]): number { | |
// Map from given x-coordinates to given y-coordinates | |
const pointsMap: Map<number, Set<number>> = new Map(); | |
// initialize points map | |
points.forEach((point) => { | |
const ySet = pointsMap.get(point[0]); | |
if (ySet) { | |
ySet.add(point[1]); | |
} else { | |
pointsMap.set(point[0], new Set([point[1]])); | |
} | |
}); | |
let maxArea = 0; | |
// Iterate through every pair of "diagonal" points | |
for (let p1Index = 0; p1Index < points.length; p1Index++) { | |
for (let p2Index = p1Index + 1; p2Index < points.length; p2Index++) { | |
const point1 = points[p1Index], | |
point2 = points[p2Index]; | |
const x1 = point1[0], | |
y1 = point1[1], | |
x2 = point2[0], | |
y2 = point2[1]; | |
const area = Math.abs((x2 - x1) * (y2 - y1)); | |
// check if the other diagonal points were given | |
const hasOtherCorners = pointsMap.get(x1)?.has(y2) && pointsMap.get(x2)?.has(y1); | |
if (hasOtherCorners && area > maxArea) { | |
maxArea = area; | |
} | |
} | |
} | |
return maxArea | |
} | |
// Example | |
const points: Point[] = [[0, 0], [2, 2], [0, 1], [4, 5], [1, 0], [-3, 5], [1, 1], [-3, -3], [0, 0], [0, 1], [2, 0], [0, 2], [4, -3]]; | |
largestRectArea(points) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment