1003. Cosine Similarity Between Two Vectors
Medium · Math
Compute the cosine similarity between two vectors.
cos_sim(a, b) = (a · b) / (||a|| * ||b||)
Foundation of dense retrieval, RAG, and embedding-based search.
Input (stdin, JSON): { "a": [1, 2, 3], "b": [4, 5, 6] }
Output (stdout): the similarity rounded to 6 decimal places.
Edge cases: zero vector → output 0.0 (avoid div-by-zero).
Examples
Example 1
Input: {"a":[1,2,3],"b":[4,5,6]}
Output: 0.974632
Explanation: Highly similar direction.Example 2
Input: {"a":[1,0],"b":[0,1]}
Output: 0.0
Explanation: Orthogonal.Constraints
- Vectors have same length, 1..1000 elements.
- Components are integers or floats in [-1e6, 1e6].