Loading…
Euclidean Distance is a easy coding interview question covering math, machine learning — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Implement a function that computes the Euclidean (L2) distance between two n-dimensional points.
Formula: sqrt(sum of (a_i - b_i)^2 for all dimensions i)
Example: [1,2,3] and [4,6,3] -> sqrt(9+16+0) = 5.0
This is the default distance metric in K-Nearest Neighbors (KNN) and clustering algorithms like K-Means. Understanding distance metrics is foundational for ML.
Try it yourself first
In an interview you'd get about 15 minutes for a easy question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Euclidean (L2) distance is the straight-line distance between two points in n-dimensional space. It is the standard metric for KNN classifiers, K-Means clustering, and low-dimensional spatial search.
| 1 | import math |
| 2 | |
| ▶ | def euclidean_distance(p1: list[float], p2: list[float]) -> float: |
| ▶ | return math.sqrt(sum((a - b) ** 2 for a, b in zip(p1, p2))) |
| 5 | |
| 6 | # NumPy version |
| 7 | import numpy as np |
| 8 | |
| 9 | def euclidean_distance_np(p1, p2): |
| 10 | return np.linalg.norm(np.array(p1) - np.array(p2)) |
Compute element-wise squared differences: (4-1)²=9, (6-2)²=16, (3-3)²=0.
Key Insights
A full interview loop is more than one round. These are the others, each with what is on the site for it.