Calculate distance between two points
Calculate the Euclidean distance between two points in a two-dimensional coordinate plane.
Course progress
Problem 69 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
first = (1, 2); second = (4, 6)
Expected output
5.0
What is happening?
The coordinate differences are 3 and 4. The distance is sqrt(3^2 + 4^2) = sqrt(25) = 5.0.
Solution strategy
Build the right mental model
Find the horizontal and vertical differences, square and add them, then take the square root.
Core concepts
geometry · Math.Sqrt
Complexity
Time O(1), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for distance-between-points
using System;
class Program
{
static double Distance(double x1, double y1, double x2, double y2)
{
double dx = x2 - x1;
double dy = y2 - y1;
return Math.Sqrt(dx * dx + dy * dy);
}
static void Main()
{
Console.WriteLine(Distance(1, 2, 4, 6).ToString("0.0"));
}
}Knowledge check
Questions students often ask
What is the main idea behind calculate distance between two points?
Find the horizontal and vertical differences, square and add them, then take the square root.
What is the time and space complexity of this solution?
Time O(1), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.