




Sponsored
Sponsored
This approach leverages the property that a square consists of four equal side lengths and two larger equal diagonal lengths. By calculating the distances between every pair of points, sorting these distances, and comparing them, we can validate the square.
Time Complexity: O(1) - The process involves constant time operations for the four points.
Space Complexity: O(1) - We only use a fixed amount of extra space.
1var validSquare = function(p1, p2, p3, p4) {
2    function dist(a, b) {
3        return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;
4    }
5    let points = [p1, p2, p3, p4];
6    let dists = [];
7    for (let i = 0; i < 4; i++) {
8        for (let j = i + 1; j < 4; j++) {
9            dists.push(dist(points[i], points[j]));
10        }
11    }
12    dists.sort((a, b) => a - b);
13    return dists[0] > 0 && dists[0] === dists[1] && dists[1] === dists[2] && dists[2] === dists[3] && dists[4] === dists[5];
14};The JavaScript implementation follows the same logic as the Python solution. It uses a nested loop to calculate all six distances, pushes these into an array, and sorts the array. The final condition checks ensure the properties of a square.
This approach calculates vectors for the sides and diagonals and applies vector dot products to verify perpendicularity (90-degree angles) and equality in length, ensuring all four sides and two diagonals satisfy the square properties.
Time Complexity: O(1) - Fixed operations per four points.
Space Complexity: O(1) - Requires a constant amount of space for storing calculations.
1class Solution {
2    private int dist
The Java solution leverages calculating distances in a manner similar to norms of vectors, utilizing sorted indices to verify required conditions for sides and diagonals. This logic maintains computational simplicity while ensuring perfect geometric conditions for a square.