Join Our 5-Week ML/AI Engineer Interview Bootcamp πŸš€ led by ML Tech Leads at FAANGs

Back to Questions

69. Cosine similarity

easy
GeneralGeneral
senior

Compute cosine similarity between two vectors, a common linear algebra measure of how aligned they are. It’s especially useful when you care about direction more than magnitude.

Requirements

Implement the function

python

Rules:

  • Use the formula: cos⁑(x,y)=βˆ‘i=1nxiyiβˆ‘i=1nxi2βˆ‘i=1nyi2\cos(x, y) = \frac{\sum_{i=1}^{n} x_i y_i}{\sqrt{\sum_{i=1}^{n} x_i^2}\sqrt{\sum_{i=1}^{n} y_i^2}}
  • Return a single float.
  • Do not use any prebuilt similarity/distance utilities (e.g., from scipy).
  • Use NumPy for vector operations (np.dot, np.linalg.norm).

Example

python

Output:

python
Input Signature
ArgumentType
xnp.ndarray
ynp.ndarray
Output Signature
Return NameType
valuefloat

Constraints

  • Use only NumPy; no SciPy similarity functions.

  • Return a single Python float.

  • Inputs same length; treat as 1D vectors.

Hint 1

Use np.dot(x, y) to compute the dot product (numerator).

Hint 2

Compute L2 norms using np.linalg.norm(x) and np.linalg.norm(y) (denominator).

Hint 3

Return dot / (norm_x * norm_y); guard against division by zero if needed.

Roles
ML Engineer
AI Engineer
Data Scientist
Quantitative Analyst
Companies
GeneralGeneral
Levels
senior
entry
Tags
numpy
linear-algebra
cosine-similarity
vector-math
31 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit