Valid Square
Problem
Given 4 points, return whether they form a non-degenerate square.
p1=[0,0] p2=[1,1] p3=[1,0] p4=[0,1]Truedef valid_square(p1, p2, p3, p4):
def d2(a, b): return (a[0]-b[0])**2 + (a[1]-b[1])**2
pts = [p1, p2, p3, p4]
ds = sorted(d2(pts[i], pts[j]) for i in range(4) for j in range(i+1, 4))
return ds[0] > 0 and ds[0] == ds[1] == ds[2] == ds[3] and ds[4] == ds[5] == 2*ds[0]
function validSquare(p1, p2, p3, p4) {
const d2 = (a, b) => (a[0]-b[0])**2 + (a[1]-b[1])**2;
const pts = [p1, p2, p3, p4];
const ds = [];
for (let i = 0; i < 4; i++) for (let j = i+1; j < 4; j++) ds.push(d2(pts[i], pts[j]));
ds.sort((a, b) => a - b);
return ds[0] > 0 && ds[0] === ds[3] && ds[4] === ds[5] && ds[4] === 2*ds[0];
}
boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[][] p = {p1, p2, p3, p4};
int[] d = new int[6]; int k = 0;
for (int i = 0; i < 4; i++) for (int j = i+1; j < 4; j++) d[k++] = (p[i][0]-p[j][0])*(p[i][0]-p[j][0]) + (p[i][1]-p[j][1])*(p[i][1]-p[j][1]);
Arrays.sort(d);
return d[0] > 0 && d[0] == d[3] && d[4] == d[5] && d[4] == 2 * d[0];
}
bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) {
vector> p = {p1, p2, p3, p4};
vector d;
for (int i = 0; i < 4; i++) for (int j = i+1; j < 4; j++) {
int dx = p[i][0]-p[j][0], dy = p[i][1]-p[j][1]; d.push_back(dx*dx + dy*dy);
}
sort(d.begin(), d.end());
return d[0] > 0 && d[0] == d[3] && d[4] == d[5] && d[4] == 2 * d[0];
}
Explanation
A square has a very clean signature in terms of distances: among the six pairwise distances between its four corners, four are equal (the sides) and two are equal and longer (the diagonals). We use squared distances to avoid square roots entirely.
We compute all six squared distances d2(a, b) = (a[0]-b[0])^2 + (a[1]-b[1])^2 and sort them. In a valid square the sorted list looks like [s, s, s, s, D, D] where the four sides are equal and the two diagonals are equal.
The check is: the smallest distance is positive (so points are distinct), the four smallest are equal, and the two largest equal each other AND equal 2 * side. That last part, diagonal = 2 * side (in squared terms), is the Pythagorean relationship that pins it to a true square rather than a rhombus.
Example: p1=[0,0], p2=[1,1], p3=[1,0], p4=[0,1]. The squared distances sort to [1, 1, 1, 1, 2, 2]. Four sides of 1, two diagonals of 2 = 2*1 → valid square, returns true.
Requiring ds[0] > 0 rules out degenerate cases where points coincide, so only a genuine non-zero-area square passes.