Leetcode 593: Valid Square

grid47
grid47
Exploring patterns and algorithms
Sep 8, 2024 5 min read

A square being validated, with each corner softly glowing as the square is checked for correctness.
Solution to LeetCode 593: Valid Square Problem

Given four points in a 2D space, determine if these points form a valid square. The points are not necessarily provided in any particular order.
Problem
Approach
Steps
Complexity
Input: The input consists of four points, each represented as an array of two integers [x, y], where x and y are the coordinates of the point in the 2D plane.
Example: Input: p1 = [0, 0], p2 = [1, 1], p3 = [1, 0], p4 = [0, 1]
Constraints:
• Each point is represented by two integers, xi and yi, where -10^4 ≤ xi, yi ≤ 10^4.
• The input will always contain exactly four points.
Output: Return 'true' if the four points form a valid square, otherwise return 'false'.
Example: Output: 'true'
Constraints:
• The output is a boolean value indicating whether the points form a valid square.
Goal: To check if the four given points form a valid square by ensuring equal side lengths and 90-degree angles.
Steps:
• Calculate the pairwise distances between the four points.
• Check if there are two unique distances: one for the sides (which should appear four times) and one for the diagonals (which should appear twice).
• Ensure that the diagonals are longer than the sides, as they should be the hypotenuses of the right triangles formed by the sides.
Goal: The points will always form valid coordinates within the range [-10^4, 10^4]. There will be exactly four points provided.
Steps:
• The number of points is always four.
• The coordinates of the points are within the range [-10^4, 10^4].
Assumptions:
• The input will always contain four valid points, and the points are not guaranteed to be ordered in any way.
Input: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Explanation: These points form a square as they have equal sides and the diagonals are equal.

Input: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Explanation: These points do not form a square as the sides are not equal.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus