DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Valid Square

Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.

The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.

A valid square has four equal sides with positive length and four equal angles (90-degree angles).

Example 1:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true

Example 2:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Output: false

Example 3:

Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]
Output: true

Constraints:

  • p1.length == p2.length == p3.length == p4.length == 2
  • -104 <= xi, yi <= 104

SOLUTION:

class Solution:
    def dist(self, a, b):
        return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])

    def isPerpendicular(self, a, b, c, d):
        return (b[1] - a[1]) * (d[1] - c[1]) == (b[0] - a[0]) * (c[0] - d[0])

    def midPoint(self, a, b):
        return (a[0] + b[0], a[1] + b[1])

    def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
        plist = [p1, p2, p3, p4]
        points = [[(0, 1), (2, 3)], [(0, 2), (1, 3)], [(0, 3), (1, 2)]]
        for diag in points:
            a, b = [plist[d] for d in diag[0]]
            c, d = [plist[d] for d in diag[1]]
            isBisector = self.midPoint(a, b) == self.midPoint(c, d)
            if not isBisector:
                continue
            d1, d2 = self.dist(a, b), self.dist(c, d)
            if d1 != d2 or d1 == 0:
                continue
            if self.isPerpendicular(a, b, c, d):
                return True
        return False
Enter fullscreen mode Exit fullscreen mode

Top comments (0)