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.

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

Solve this problem on LeetCode: Click Here

Valid Square Java Solution

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)};
        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
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala