Problem Description
Given four points in the 2D plane (provided in any order), determine whether these points form a valid square. A valid square must have four equal sides with positive length and four right angles.
Key Insights
- Calculate all six pairwise squared distances between the four points.
- For a valid square, there should be exactly two unique distances: the smaller one representing the sides (appearing exactly 4 times) and the larger one representing the diagonals (appearing exactly 2 times).
- Duplicate points or a zero distance immediately disqualify the formation of a square.
Space and Time Complexity
Time Complexity: O(1) (since the number of points is fixed) Space Complexity: O(1) (constant extra space used for computations)
Solution
We start by calculating the squared Euclidean distance between every pair of points to avoid the complications of floating point precision. We then count the frequency of these distances. A valid square must show exactly two distinct distances: one (side length squared) should appear 4 times and the other (diagonal length squared) should appear 2 times. This provides a robust check for both equal sides and the correct geometric property (diagonals in a square are longer than sides and appear exactly twice). The solution uses simple iteration over the fixed set of point pairs to tally frequencies and then verifies the required counts.