Given the coordinates of four points in 2D space, determine if the four points can construct a square.
The input is four points in the format (x, y). You need to write a function:
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4)
where p1
, p2
, p3
, and p4
are arrays representing the coordinates of the points.
Here is the Java code implementing the above approach:
public class ValidSquare {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[] distances = {
distanceSquared(p1, p2), distanceSquared(p1, p3),
distanceSquared(p1, p4), distanceSquared(p2, p3),
distanceSquared(p2, p4), distanceSquared(p3, p4)
};
Arrays.sort(distances);
// Check that we have 4 sides (equal smaller lengths) and 2 diagonals (equal larger lengths)
return distances[0] > 0 &&
distances[0] == distances[1] &&
distances[0] == distances[2] &&
distances[0] == distances[3] &&
distances[4] == distances[5] &&
distances[4] > distances[3];
}
private int distanceSquared(int[] a, int[] b) {
return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
}
}
This algorithm runs in constant time (O(1)) since it neither depends on input size (always 4 points) nor complex operations beyond fixed-distance computations and fixed-size sorting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?