LeetCode Solutions

593. Valid Square

Time: $O(4^2) = O(1)$

Space: $O(1)$

			

class Solution {
 public:
  bool validSquare(vector<int>& p1, vector<int>& p2,
                   vector<int>& p3, vector<int>& p4) {
    unordered_set<int> distSet;
    vector<vector<int>> points{p1, p2, p3, p4};

    for (int i = 0; i < 4; ++i)
      for (int j = i + 1; j < 4; ++j)
        distSet.insert(dist(points[i], points[j]));

    return !distSet.count(0) && distSet.size() == 2;
  }

 private:
  int dist(vector<int>& p1, vector<int>& p2) {
    return (p1[0] - p2[0]) * (p1[0] - p2[0]) +
           (p1[1] - p2[1]) * (p1[1] - p2[1]);
  }
};
			

class Solution {
  public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
    Set<Integer> distSet = new HashSet<>();
    int[][] points = {p1, p2, p3, p4};

    for (int i = 0; i < 4; ++i)
      for (int j = i + 1; j < 4; ++j)
        distSet.add(dist(points[i], points[j]));

    return !distSet.contains(0) && distSet.size() == 2;
  }

  private int dist(int[] p1, int[] p2) {
    return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
  }
}
			

class Solution:
  def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
    def dist(p1: List[int], p2: List[int]) -> int:
      return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2

    distSet = set([dist(*pair)
                   for pair in list(itertools.combinations([p1, p2, p3, p4], 2))])

    return 0 not in distSet and len(distSet) == 2