Implement Cosine Similarity Function for String Vectors
Company: Shopify
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of vector-space similarity and text representation by asking for a cosine similarity computation over string-derived vectors, testing coding and algorithmic skills relevant to data science and text processing.
Constraints
- 0 <= len(a), len(b) <= 10^5
- Strings may contain letters, digits, punctuation, and whitespace.
- Tokenization is case-insensitive and considers maximal runs of [a-z0-9] as words.
- Return a float rounded to 6 decimal places; return 0.0 when either string yields no tokens.
Examples
Input: ("the cat sat", "the cat sat")
Expected Output: 1.0
Explanation: Identical bag-of-words vectors point in the same direction, so cosine similarity is exactly 1.0.
Input: ("the cat", "the dog")
Expected Output: 0.5
Explanation: Both vectors are [1,1] over their union {the,cat,dog}; they share only "the". dot=1, magnitudes=sqrt(2) each, so 1/2 = 0.5.
Hints
- Tokenize each string into lowercase words (a simple approach: split on non-alphanumeric characters and drop empties), then build a frequency Counter for each.
- Cosine similarity = dot(u, v) / (|u| * |v|). The dot product only needs the words common to both vectors; the magnitude is sqrt(sum of squared counts).
- Guard the empty/no-token case explicitly to avoid dividing by a zero magnitude, and round the final value to 6 decimal places.