learn deep. ship safe.Practice testsFollow ByteMunSubscribe

easyEmbeddingsVectors

Cosine Similarity of Embeddings

Compute the cosine similarity of two embedding vectors, the score behind semantic search and RAG retrieval, and handle the zero-vector edge case correctly.

JavaScript or Python

Embeddings represent text as vectors, and semantic search ranks documents by how closely their vector points in the same direction as the query's. Given two vectors a and b of the same length, return their cosine similarity: the dot product divided by the product of their lengths (Euclidean norms).

If either vector has length zero (all zeros), return 0 instead of dividing by zero. Results are checked to six significant digits.

Examples

Example 1

Input: a = [1, 0], b = [0, 1]
Output: 0
Why: Perpendicular vectors are unrelated

Example 2

Input: a = [1, 2, 3], b = [2, 4, 6]
Output: 1
Why: Same direction, different length

Constraints

  • 1 <= a.length == b.length <= 4096
  • -1000 <= a[i], b[i] <= 1000

Hints

Hint 1

Compute the dot product and both norms in one loop.

Hint 2

Check for a zero norm before dividing.

Solution

Show the solution (try it yourself first)

Cosine similarity is a·b / (|a| |b|). Accumulate the dot product and the two sums of squares in a single pass, take square roots for the norms, and guard against a zero norm, which would otherwise give a division by zero (or NaN).

def cosine_similarity(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    na = sum(x * x for x in a) ** 0.5
    nb = sum(y * y for y in b) ** 0.5
    if na == 0 or nb == 0:
        return 0.0
    return dot / (na * nb)

Complexity

Time O(n) for vectors of length n, space O(1). In production you usually normalise embeddings to length 1 once when you store them; then cosine similarity is just the dot product, which vector databases compute very fast. Interviewers often ask why cosine is preferred over Euclidean distance for text: it ignores vector length and compares direction, which is where the meaning lives.

Found a mistake in this problem, its tests or the solution?

Written by Published Tests checked by Deepak
Case 1Input: [1,0], [0,1]Expected: 0
Case 2Input: [1,2,3], [2,4,6]Expected: 1

Run checks these 2 samples. Submit checks all 7 tests, including hidden ones.

  1. Top-K Similar DocumentsRAG · Retrieval · Embeddings
    medium
  2. Pair with Target SumArrays · Hash map
    easy
  3. Balanced BracketsStack · Strings
    easy
  4. Palindrome SentenceStrings · Two pointers
    easy