Skip to main content
Back to problems
#593
Medium Algorithms

Valid square

Math Geometry
44.9% acceptance
Jan 13, 2026
1117
913
Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles).

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn valid_square(p1: Vec<i32>, p2: Vec<i32>, p3: Vec<i32>, p4: Vec<i32>) -> bool {
    fn d(a: &[i32], b: &[i32]) -> i32 { (a[0]-b[0]).pow(2) + (a[1]-b[1]).pow(2) }
    let mut dists = [
      d(&p1,&p2), d(&p1,&p3), d(&p1,&p4),
      d(&p2,&p3), d(&p2,&p4), d(&p3,&p4),
    ];
    dists.sort_unstable();
    dists[0] > 0 && dists[0]==dists[1] && dists[1]==dists[2] && dists[2]==dists[3] && dists[4]==dists[5]
  }
}