Distance Calculator - Problem

Write a function to calculate the Euclidean distance between two points in 2D space. The distance between points (x1, y1) and (x2, y2) is calculated using the formula:

distance = √((x2 - x1)² + (y2 - y1)²)

The function should take two arrays as input: point1 = [x1, y1] and point2 = [x2, y2], and return the distance as a floating-point number rounded to 2 decimal places.

Extension: The same approach can be easily extended to 3D space using distance = √((x2 - x1)² + (y2 - y1)² + (z2 - z1)²)

Input & Output

Example 1 — Basic 2D Distance
$ Input: point1 = [3, 4], point2 = [7, 1]
Output: 5.00
💡 Note: Distance = √((7-3)² + (1-4)²) = √(4² + (-3)²) = √(16 + 9) = √25 = 5.00
Example 2 — Same Point
$ Input: point1 = [0, 0], point2 = [0, 0]
Output: 0.00
💡 Note: Distance between identical points is 0: √((0-0)² + (0-0)²) = √(0 + 0) = 0.00
Example 3 — Negative Coordinates
$ Input: point1 = [-2, -3], point2 = [1, 1]
Output: 5.00
💡 Note: Distance = √((1-(-2))² + (1-(-3))²) = √(3² + 4²) = √(9 + 16) = √25 = 5.00

Constraints

  • -100 ≤ coordinates ≤ 100
  • Result rounded to 2 decimal places
  • Points are in 2D coordinate system

Visualization

Tap to expand
INPUTALGORITHMRESULTP1(3,4)P2(7,1)distance?Coordinate PointsPoint 1: [3, 4]Point 2: [7, 1]1Calculate differencesdx = 7 - 3 = 4dy = 1 - 4 = -32Square the differencesdx² = 16, dy² = 93Apply distance formula√(16 + 9) = √25 = 5.05.00Distance(2 decimal places)✓ Pythagorean theorem✓ Precise calculation✓ Rounded outputKey Insight:The Euclidean distance formula √((x₂-x₁)² + (y₂-y₁)²) directly gives the shortest path between any two points in 2D space.TutorialsPoint - Distance Calculator | Direct Formula Application
Asked in
Google 15 Microsoft 12 Apple 8 Amazon 10
15.0K Views
Medium Frequency
~10 min Avg. Time
350 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen