Shortest Distance in a Plane

medium database sql

Problem

Point2D(x, y). Return the shortest distance between any two distinct points (rounded to 2 dp).

Inputp=[(-1,-1),(0,0),(-1,-2)]
Output1.00
(-1,-1) to (-1,-2) is the closest pair.

SELECT ROUND(MIN(SQRT(POW(a.x - b.x, 2) + POW(a.y - b.y, 2))), 2) AS shortest
FROM Point2D a JOIN Point2D b ON (a.x, a.y) <> (b.x, b.y);
Time: O(n) Space: O(n)