KatInterview

593. Valid Square

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if four given 2D points can form a valid square. The input points p1, p2, p3, and p4 are not provided in any specific order. A square has four equal sides and four 90-degree angles. This also implies that its two diagonals are equal in length.

Solution

Valid Square in Python

class Solution:
    def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
        
        # Helper function to calculate the squared distance between two points.
        # Using squared distance avoids floating point issues and is computationally faster.
        def distSq(pa, pb):
            return (pa[0] - pb[0])**2 + (pa[1] - pb[1])**2

        # There are C(4, 2) = 6 distances between 4 points.
        # We store their squared values in a list.
        dists = [
            distSq(p1, p2),
            distSq(p1, p3),
            distSq(p1, p4),
            distSq(p2, p3),
            distSq(p2, p4),
            distSq(p3, p4)
        ]

        # Sort the distances to easily identify sides and diagonals.
        dists.sort()

        # For a valid square, we must have:
        # 1. All side lengths must be positive (no two points are the same).
        #    This means the smallest distance must be > 0.
        # 2. Four equal side lengths (the 4 smallest distances).
        # 3. Two equal diagonal lengths (the 2 largest distances).
        # 4. The diagonal's squared length is twice the side's squared length (Pythagorean theorem).
        return (
            dists[0] > 0 and
            dists[0] == dists[1] == dists[2] == dists[3] and
            dists[4] == dists[5] and
            dists[4] == 2 * dists[0]
        )

Valid Square in Java

class Solution {
    // Helper function to calculate the squared distance between two points.
    // Using squared distance avoids floating point issues and is computationally faster.
    private long distSq(int[] p1, int[] p2) {
        long dx = p1[0] - p2[0];
        long dy = p1[1] - p2[1];
        return dx * dx + dy * dy;
    }

    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        // There are C(4, 2) = 6 distances between 4 points.
        // We store their squared values in an array.
        long[] dists = new long[6];
        dists[0] = distSq(p1, p2);
        dists[1] = distSq(p1, p3);
        dists[2] = distSq(p1, p4);
        dists[3] = distSq(p2, p3);
        dists[4] = distSq(p2, p4);
        dists[5] = distSq(p3, p4);

        // Sort the distances to easily identify sides and diagonals.
        Arrays.sort(dists);

        // For a valid square, we must have:
        // 1. All side lengths must be positive (no two points are the same).
        //    This means the smallest distance must be > 0.
        // 2. Four equal side lengths (the 4 smallest distances).
        // 3. Two equal diagonal lengths (the 2 largest distances).
        // 4. The diagonal's squared length is twice the side's squared length (Pythagorean theorem).
        return dists[0] > 0 &&
               dists[0] == dists[1] && 
               dists[1] == dists[2] && 
               dists[2] == dists[3] &&
               dists[4] == dists[5] &&
               dists[4] == 2 * dists[0];
    }
}

Valid Square in C++

class Solution {
public:
    // Helper function to calculate the squared distance between two points.
    // Using squared distance avoids floating point issues and is computationally faster.
    long long distSq(vector<int>& p1, vector<int>& p2) {
        long long dx = p1[0] - p2[0];
        long long dy = p1[1] - p2[1];
        return dx * dx + dy * dy;
    }

    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
        // There are C(4, 2) = 6 distances between 4 points.
        // We store their squared values in a vector.
        vector<long long> dists;
        dists.push_back(distSq(p1, p2));
        dists.push_back(distSq(p1, p3));
        dists.push_back(distSq(p1, p4));
        dists.push_back(distSq(p2, p3));
        dists.push_back(distSq(p2, p4));
        dists.push_back(distSq(p3, p4));

        // Sort the distances to easily identify sides and diagonals.
        sort(dists.begin(), dists.end());

        // For a valid square, we must have:
        // 1. All side lengths must be positive (no two points are the same).
        //    This means the smallest distance must be > 0.
        // 2. Four equal side lengths (the 4 smallest distances).
        // 3. Two equal diagonal lengths (the 2 largest distances).
        // 4. The diagonal's squared length is twice the side's squared length (Pythagorean theorem).
        return dists[0] > 0 &&
               dists[0] == dists[1] && 
               dists[1] == dists[2] && 
               dists[2] == dists[3] &&
               dists[4] == dists[5] &&
               dists[4] == 2 * dists[0];
    }
};

Valid Square in TypeScript

function validSquare(p1: number[], p2: number[], p3: number[], p4: number[]): boolean {
    // Helper function to calculate the squared distance between two points.
    // Using squared distance avoids floating point issues and is computationally faster.
    const distSq = (pa: number[], pb: number[]): number => {
        return Math.pow(pa[0] - pb[0], 2) + Math.pow(pa[1] - pb[1], 2);
    };

    // There are C(4, 2) = 6 distances between 4 points.
    // We store their squared values in an array.
    const dists = [
        distSq(p1, p2),
        distSq(p1, p3),
        distSq(p1, p4),
        distSq(p2, p3),
        distSq(p2, p4),
        distSq(p3, p4)
    ];

    // Sort the distances to easily identify sides and diagonals.
    dists.sort((a, b) => a - b);

    // For a valid square, we must have:
    // 1. All side lengths must be positive (no two points are the same).
    //    This means the smallest distance must be > 0.
    // 2. Four equal side lengths (the 4 smallest distances).
    // 3. Two equal diagonal lengths (the 2 largest distances).
    // 4. The diagonal's squared length is twice the side's squared length (Pythagorean theorem).
    return (
        dists[0] > 0 &&
        dists[0] === dists[1] &&
        dists[1] === dists[2] &&
        dists[2] === dists[3] &&
        dists[4] === dists[5] &&
        dists[4] === 2 * dists[0]
    );
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.