L2-Normalize a 1D Embedding Vector

Basics
BasicsEmbeddingsNumPyOpenAIAnthropicGoogle

Problem

Implement l2_normalize(v) that scales a 1D embedding vector v to unit Euclidean length (∥v∥2=1\|v\|_2 = 1). If v is the all-zeros vector (∥v∥2=0\|v\|_2 = 0), return a zero array of the same shape.

Why It Matters: Vector databases (FAISS, pgvector, Pinecone) pre-normalize embeddings to unit length so cosine similarity simplifies to a fast raw dot product.

Function Signature

import numpy as np

def l2_normalize(v) -> np.ndarray:
    """Scale a 1D vector to unit L2 norm."""

Sample Input & Output

Example 1: 3-4-5 Right Triangle Vector

Input:

v = [3.0, 4.0]

Expected Output:

array([0.6, 0.8])

Explanation: L2 norm is 32+42=5.0\sqrt{3^2 + 4^2} = 5.0, so dividing yields [3/5, 4/5] = [0.6, 0.8] with norm 1.0.

Example 2: All-Zeros Guard

Input:

v = [0.0, 0.0, 0.0]

Expected Output:

array([0.0, 0.0, 0.0])

Explanation: Guarding against norm == 0.0 prevents NaN from division by zero.

Constraints & Edge Cases

  • Return a 1D float NumPy array of unit L2 norm (or zeros for zero vector).
  • Return a float np.ndarray of the same shape as v.
  • Handle Python lists or NumPy arrays seamlessly via np.asarray(v, dtype=float).

Constraints & Evaluation Criteria

  • Return a 1D float NumPy array of unit L2 norm (or zeros for zero vector).

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[3.0, 4.0]
Expected Output / Criteria
[0.6, 0.8]