LeetCode 0593. Valid Square Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0

Description

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

Solutions

Solution 1

PythonJavaC++Go
class Solution: def validSquare( self, p1: List[int], p2: List[int], p3: List[int], p4: List[int] ) -> bool: def check(a, b, c): (x1, y1), (x2, y2), (x3, y3) = a, b, c d1 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) d2 = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3) d3 = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3) return any( [ d1 == d2 and d1 + d2 == d3 and d1, d2 == d3 and d2 + d3 == d1 and d2, d1 == d3 and d1 + d3 == d2 and d1, ] ) return ( check(p1, p2, p3) and check(p2, p3, p4) and check(p1, p3, p4) and check(p1, p2, p4) )(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !