Similar Problems
Similar Problems not available
Valid Square - Leetcode Solution
Companies:
LeetCode: Valid Square Leetcode Solution
Difficulty: Medium
Topics: math
Problem:
Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example 1:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
Solution:
To solve this problem, we need to check whether the given four points form a valid square. A square can be defined by four sides of equal lengths and four right angles.
To check the sides of the square, we can find the distance between each pair of points and store it in a set. If the set contains four distinct values, then the sides are of equal length, and we can move ahead with checking the angles.
To check the right angles of the square, we need to find the dot product of the vectors formed by any two pairs of adjacent points. If the dot product is zero, then the two vectors are perpendicular to each other, indicating that the angle is right.
If the two vectors are not perpendicular, then the points do not form a square.
We can check all the pairs of adjacent points and ensure that all four angles are right angles.
Finally, we can return true if all the above conditions are satisfied, indicating that the given four points form a valid square, otherwise return false.
Here is the Python code implementation of the solution:
class Solution:
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
# Create a set to store the distances between all pairs of points
lengths = set()
lengths.add(self.getDistance(p1, p2))
lengths.add(self.getDistance(p1, p3))
lengths.add(self.getDistance(p1, p4))
lengths.add(self.getDistance(p2, p3))
lengths.add(self.getDistance(p2, p4))
lengths.add(self.getDistance(p3, p4))
# Check if there are exactly two unique distances
if len(lengths) != 2:
return False
# Check if all four angles are 90 degrees
angles = []
angles.append(self.getAngle(p1, p2, p3))
angles.append(self.getAngle(p1, p3, p2))
angles.append(self.getAngle(p1, p4, p2))
angles.append(self.getAngle(p3, p4, p2))
for angle in angles:
if angle != 90:
return False
return True
# Calculate the Euclidean distance between two points
def getDistance(self, p1: List[int], p2: List[int]) -> int:
x1, y1 = p1
x2, y2 = p2
dx = x2 - x1
dy = y2 - y1
return dx * dx + dy * dy
# Calculate the angle between three points
def getAngle(self, p1: List[int], p2: List[int], p3: List[int]) -> int:
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
dx1 = x2 - x1
dy1 = y2 - y1
dx2 = x3 - x2
dy2 = y3 - y2
dot = dx1 * dx2 + dy1 * dy2
cosAngle = dot / (self.getDistance(p1, p2) * self.getDistance(p2, p3))
return round(math.degrees(math.acos(cosAngle)))
Valid Square Solution Code
1