LeetCode 593: Valid Square Solution

Master LeetCode problem 593 (Valid Square), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

593. Valid Square

Problem Explanation

Explanation

To determine if the four given points form a square, we can calculate the distances between all pairs of points. In a square, there are 4 sides of equal length and 2 diagonals of equal length. Additionally, the distances must satisfy the Pythagorean theorem. We can calculate the distance between two points using the Euclidean distance formula: distance = sqrt((x2 - x1)^2 + (y2 - y1)^2).

Algorithm

  1. Calculate the distances between all pairs of points.
  2. Find the minimum and maximum distances.
  3. Check if there are 4 equal distances (sides) and 2 equal distances (diagonals).
  4. Verify that the distance verification satisfies the Pythagorean theorem for a square.
  5. Return true if the conditions are met, otherwise return false.

Time Complexity

The time complexity of this algorithm is O(1) since we are performing a constant number of operations regardless of the input size.

Space Complexity

The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        int[][] points = {p1, p2, p3, p4};
        Set<Integer> distances = new HashSet<>();
        
        for (int i = 0; i < points.length; i++) {
            for (int j = i + 1; j < points.length; j++) {
                int dist = (int) (Math.pow(points[j][0] - points[i][0], 2) + Math.pow(points[j][1] - points[i][1], 2));
                distances.add(dist);
            }
        }
        
        if (distances.size() != 2) return false;
        
        List<Integer> sortedDistances = new ArrayList<>(distances);
        Collections.sort(sortedDistances);
        
        return sortedDistances.get(0) > 0 && sortedDistances.get(0) == sortedDistances.get(1) / 2 && sortedDistances.get(1) == 2 * sortedDistances.get(0);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 593 (Valid Square)?

This page provides optimized solutions for LeetCode problem 593 (Valid Square) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 593 (Valid Square)?

The time complexity for LeetCode 593 (Valid Square) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 593 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 593 in Java, C++, or Python.

Back to LeetCode Solutions