CODING CHALLENGE · N°05

Cosine Similarity

Easy AI EngineeringEmbeddingsMath

The measure behind every embedding search and RAG system: how aligned are two vectors, regardless of their length? It is the dot product divided by both magnitudes — 1 means identical direction, 0 orthogonal, -1 opposite.

The problem

Given two equal-length vectors a and b, return their cosine similarity: dot(a, b) / (‖a‖ · ‖b‖), where ‖v‖ is the Euclidean norm (square root of the sum of squares). The result lies in [-1, 1] and ignores vector length — only direction matters.

EXAMPLE 1
Input a = [1, 2, 3], b = [1, 2, 3]
Output 1.0
same direction
EXAMPLE 2
Input a = [1, 0], b = [0, 1]
Output 0.0
orthogonal
EXAMPLE 3
Input a = [1, 0], b = [-1, 0]
Output -1.0
opposite
EXAMPLE 4
Input a = [1, 1], b = [2, 2]
Output 1.0
length does not matter
CONSTRAINTS
  • len(a) == len(b) ≥ 1, and neither vector is all zeros.
  • Result in [-1, 1], within floating-point tolerance.
  • Cosine ignores magnitude — scaling a vector does not change the answer.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement cosine_similarity(a, b) = dot product of a and b, divided by the product of their Euclidean norms.

HINTS — 4 IDEAS
  1. The dot product is the sum of element-wise products: Σ aᵢ·bᵢ.
  2. The Euclidean norm of v is sqrt(Σ vᵢ²).
  3. Divide the dot product by ‖a‖ · ‖b‖ to cancel out length and leave only direction.
  4. Identical vectors give 1; orthogonal give 0; opposite give -1.
CPython · WebAssembly
Approach, complexity & discussion — open after you solve

The approach

Compute the dot product of the two vectors, then divide by the product of their magnitudes: cos = (a·b) / (‖a‖‖b‖). Accumulate the dot product and both sums-of-squares in a single pass, take the square roots at the end, and guard against a zero-magnitude vector before dividing.

Complexity

Time O(d) in the dimension; space O(1) — a few running scalars, one pass.

Common mistakes

  • Returning the raw dot product without dividing by the magnitudes — then length dominates and it is no longer cosine.
  • Dividing by zero on a zero vector — guard it (define the similarity as 0 or handle explicitly).
  • Assuming the inputs are the same length without checking.

Where this shows up

Cosine similarity is the standard score for comparing embeddings — semantic search, RAG retrieval, clustering, deduplication, recommendations. On vectors that are already unit-normalized (many embedding models return these) it reduces to a plain dot product, which is exactly why vector databases can rank by dot product and get cosine ordering for free.

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.