Solution: Valid Square

Let’s solve the Valid Square problem using the Math and Geometry pattern.

Statement

Given the coordinates of four points P1P_1, P2P_2, P3P_3, and P4P_4 in 2D space, determine if these points form a square.

Each point PiP_i is represented as [xi, yi][x_i,\space y_i], and the points may be provided in any order.

A square is defined as having:

  • Four sides of equal positive length

  • Four right angles (90 degrees)

Constraints:

  • p1.length == p2.length == p3.length == p4.length == 2

  • 104-10^4\leq xi, yix_i, \space y_i 104\leq 10^4

Solution

To determine if four points in 2D space form a square, we utilize the fundamental geometric properties of a square. A square is characterized by having four equal sides and two equal diagonals. By calculating the distances between all pairs of points, we can classify these distances into side lengths and diagonal lengths to verify the conditions of a square.

The squared distance between two points, P1(x1, y1)P_1(x1, \space y1) and P2(x2, y2)P_2(x_2, \space y_2), is calculated using the formula below:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.