Valid Square

Problem Id: 593 Difficulty: Medium


Intuition

Solution


class Solution:
    def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
        points = [p1, p2, p3, p4]
        edges = []
        for i in range(4):
            for j in range(i + 1, 4):
                edges.append(self.edge(points[i], points[j]))
        edges.sort()
        if edges[0] == 0:
            return False
        s1 = set(edges[:4])
        s2 = set(edges[4:])
        if len(s1) != 1 or len(s2) != 1:
            return False
        if 2 * s1.pop() != s2.pop():
            return False
        return True

    def edge(self, a, b):
        return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2