Euclidean Distance

EASY

Write a Python function to calculate the Euclidean distance between two points (P and Q) in N-dimensional space. The points can be represented as lists or tuples of numbers (e.g., p1 = [x1, y1, z1], p2 = [x2, y2, z2]).

The formula for Euclidean distance between points P=(p1, p2, ..., pn) and Q=(q1, q2, ..., qn) is:

Distance(P, Q) = √ [ ∑i=1n (pi - qi)2 ]

Discuss both a solution using basic Python loops and a more efficient solution using NumPy.

Examples:

Example 1 (2D):

Input: p1 = [1, 2], p2 = [4, 6]
Output: 5.0
Explanation: sqrt((4-1)^2 + (6-2)^2) = sqrt(3^2 + 4^2) = sqrt(9 + 16) = sqrt(25) = 5.0

Example 2 (3D):

Input: p1 = (0, 0, 0), p2 = (3, 4, 5)
Output: 7.0710678118654755
Explanation: sqrt(3^2 + 4^2 + 5^2) = sqrt(9 + 16 + 25) = sqrt(50)

Constraints:

  • Input points p1 and p2 will be lists or tuples of numbers.
  • p1 and p2 will have the same length (number of dimensions).
  • The number of dimensions will be at least 1.

Function Signature (Python):

from typing import List, Tuple, Union
import math
import numpy as np # For NumPy solution

class Solution:
    def euclidean_distance(self, 
                             p1: Union[List[float], Tuple[float, ...]], 
                             p2: Union[List[float], Tuple[float, ...]]) -> float:
        # Your code here (e.g., using loops)
        pass

    def euclidean_distance_numpy(self, 
                                 p1: np.ndarray, 
                                 p2: np.ndarray) -> float:
        # Your NumPy-based code here
        pass

 

Nerchuko Academy · Free DS Interview Prep