You are given the coordinates of four points in a 2D space. You have to determine if these points can form a square.
A square is a quadrilateral with all sides having equal length and all angles being 90 degrees.
#include <vector>
#include <unordered_set>
#include <cmath>
using namespace std;
class Solution {
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
// Helper function to calculate the squared distance between two points
auto distSq = [](const vector<int>& a, const vector<int>& b) {
return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
};
unordered_set<int> distances = {
distSq(p1, p2), distSq(p1, p3), distSq(p1, p4),
distSq(p2, p3), distSq(p2, p4), distSq(p3, p4)
};
// A valid square will have exactly 2 unique distances: the sides and the diagonals
if (distances.size() != 2) return false;
auto side = *distances.begin();
auto diag = *next(distances.begin());
// Ensure the smaller value corresponds to sides (it will occur 4 times)
if (side > diag) swap(side, diag);
int side_cnt = 0, diag_cnt = 0;
// Validate the counts
vector<vector<int>> points = {p1, p2, p3, p4};
for (int i = 0; i < points.size(); ++i) {
for (int j = i + 1; j < points.size(); ++j) {
int d = distSq(points[i], points[j]);
if (d == side) side_cnt++;
else if (d == diag) diag_cnt++;
else return false; // If any other distance exists, it's not a square
}
}
return side_cnt == 4 && diag_cnt == 2;
}
};
This solution efficiently checks if the given four points can form a square, ensuring all sides are equal and both diagonals are equal but longer than the sides.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?