### LeetCode - Valid Square Solution - The Coding Shala

Home >> LeetCode >> Valid Square

In this post, We will learn how to solve LeetCode's Valid Square problem and will implement a Valid Square solution in Java.

## Valid Square

Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.

Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True

## Valid Square Java Solution

Approach
We will find 4 sides and 2 diagonals length and for a valid square all 4 sides should be the same length and both diagonal also should be the same length and side and diagonal length is not the same.

Java Program:

```class Solution {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[] lengths = {length(p1, p2), length(p1, p3), length(p1, p4), length(p2, p3), length(p2,p4), length(p3,p4)};

Arrays.sort(lengths);

if(lengths == lengths) {
if(lengths == lengths && lengths == lengths && lengths == lengths) {
if(lengths != lengths) {
return true;
}
}
}

return false;
}

public int length(int[] p1, int[] p2) {
return (p2-p1)*(p2-p1) + (p2-p1)*(p2-p1);
}
}
```

Other Posts You May Like