LeetCode 593: Valid Square

link

We check side lengths and perpedicularity like below:

Time: \mathcal{O}(1), space: \mathcal{O}(1).

class Solution:
    def validSquare(
        self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]
    ) -> bool:
        def dist(a, b):
            x_dist = a[0] - b[0]
            y_dist = a[1] - b[1]
            return x_dist * x_dist + y_dist * y_dist

        def slope(a, b):
            dx = a[0] - b[0]
            dy = a[1] - b[1]

            return dy / dx if dx != 0 else float("inf")

        def is_perpendicular(slope1, slope2):
            if slope1 == float("inf"):
                return slope2 == 0
            if slope2 == float("inf"):
                return slope1 == 0

            return round(slope1 * slope2) == -1

        other_points = sorted([p2, p3, p4], key=lambda p: dist(p, p1))
        A, B, D, C = p1, other_points[0], other_points[1], other_points[2]
        if dist(A, B) != dist(A, D):
            return False

        if dist(C, B) != dist(C, D):
            return False

        slope_AB = slope(A, B)
        slope_AD = slope(A, D)
        if not is_perpendicular(slope_AB, slope_AD):
            return False

        slope_CB = slope(C, B)
        slope_CD = slope(C, D)
        if not is_perpendicular(slope_CB, slope_CD):
            return False

        return True

Leave a comment