1403. Point to Segment Distance

Medium3.5 points estimatedGeometryMaths

A drone shuttles along a straight cable between two docking pins on a flat map, and a sensor tower stands at a fixed spot. The cable is the closed segment segment = [x1, y1, x2, y2], and the two pins may coincide, in which case the cable is a single point. Given the tower position point = [px, py], return the Euclidean distance from the tower to the nearest point of the cable.

Find the nearest point by projecting the tower onto the line through the pins and clamping the position along the cable to its two ends. Use exact integer dot products for the clamping decisions so the endpoint cases never depend on rounding, and take a single square root at the end. An answer within absolute or relative error 1e-6 is accepted. The intended solution runs in O(1) time and O(1) space.

Example 1

Input:
point = [0,3], segment = [-2,0,4,0]
Output:
3
Explanation:

The foot of the perpendicular (0, 0) lies inside the segment, so the distance is 3.

Example 2

Input:
point = [7,4], segment = [0,0,4,0]
Output:
5
Explanation:

The projection falls beyond the end (4, 0), so the nearest point is that end and the distance is 5.

Example 3

Input:
point = [1,1], segment = [3,3,3,3]
Output:
2.8284271247461903
Explanation:

The segment is the single point (3, 3), so the distance is the square root of 8.

Constraints

point.length == 2, segment.length == 4

-104 ≤ every coordinate ≤ 104

Answers within absolute or relative error 1e-6 are accepted.

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…