### 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[4] == lengths[5]) {
if(lengths[0] == lengths[1] && lengths[1] == lengths[2] && lengths[2] == lengths[3]) {
if(lengths[0] != lengths[4]) {
return true;
}
}
}

return false;
}

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

Other Posts You May Like