Back to challenges
Easy 0 solved 0% acceptance

Distance Between Points

Compute the straight-line distance between two points.

What you'll learn

  • Apply the distance formula
  • Use square roots
  • Return a floating-point result

Problem

Compute the Euclidean distance between (x1, y1) and (x2, y2): the square root of (x2 − x1)² + (y2 − y1)².

Implement distance(x1, y1, x2, y2).

Input

x1: First point x. y1: First point y. x2: Second point x. y2: Second point y.

Output

Return the distance.

Constraints

-1,000,000 ≤ each coordinate ≤ 1,000,000

Examples

Example 1
Input:
x1 = 0.0
x2 = 3.0
y1 = 0.0
y2 = 4.0

Expected output:
expected = 5.0
Input:
double x1 = 0.0;
double x2 = 3.0;
double y1 = 0.0;
double y2 = 4.0;

Expected output:
double expected = 5.0;
Input:
double x1 = 0.0;
double x2 = 3.0;
double y1 = 0.0;
double y2 = 4.0;

Expected output:
double expected = 5.0;

Explanation

√(3² + 4²) = √25 = 5.

Example 2
Input:
x1 = 1.0
x2 = 1.0
y1 = 1.0
y2 = 1.0

Expected output:
expected = 0.0
Input:
double x1 = 1.0;
double x2 = 1.0;
double y1 = 1.0;
double y2 = 1.0;

Expected output:
double expected = 0.0;
Input:
double x1 = 1.0;
double x2 = 1.0;
double y1 = 1.0;
double y2 = 1.0;

Expected output:
double expected = 0.0;

Explanation

Both points are the same, so the distance is 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Compute the horizontal and vertical differences between the two points.

Hint 2

Square both differences, add them, then take the square root of the total.

Hint 3

Watch for negative coordinates, but the distance formula still works the same.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.