Shortest Distance in a Plane LeetCode Solution

Last updated on January 21st, 2025 at 10:06 pm

Here, we see the Shortest Distance in a Plane LeetCode Solution. This Leetcode problem is solved using MySQL and Pandas.

List of all LeetCode Solution

Level of Question

Medium

Shortest Distance in a Plane LeetCode Solution

Shortest Distance in a Plane LeetCode Solution

1. Problem Statement

Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane.

Write a query to find the shortest distance between these points rounded to 2 decimals.

xy
-1-1
00
-1-2

The shortest distance is 1.00 from point (-1,-1) to (-1,2). So the output should be:

shortest
1.00

2. Code Implementation in Different Languages

2.1 Shortest Distance in a Plane MySQL

select 
  round(
    min(dist), 
    2
  ) as shortest 
from 
  (
    select 
      if(
        a.x = b.x 
        and a.y = b.y, 
        10000, 
        sqrt(
          power(a.x - b.x, 2) + power(a.y - b.y, 2)
        )
      ) as dist 
    from 
      point_2d as a, 
      point_2d as b
  ) as d;
Scroll to Top