KatInterview

Word-Count Cosine Score for Two Text Strings

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-mapcountingstrings

Last updated

Compute the cosine of the angle between the word-frequency vectors of two strings, using a hash-map counter and guarding against empty inputs.

Word-Count Cosine Score

You are given two strings, first and second. Turn each one into a vector of word counts, then measure how closely the two vectors point in the same direction.

How to build the vectors

  • Split each string on whitespace, so any run of spaces, tabs or newlines separates words, and leading or trailing whitespace is ignored. Python's str.split() with no arguments does exactly this.
  • Words are compared exactly as they appear. The comparison is case-sensitive, and punctuation stays part of the word, so "Cat", "cat" and "cat," are three different words.
  • Each distinct word is one dimension of the vector. Its value is the number of times the word occurs in that string.

What to compute

The score is:

dot(A, B) / (|A| * |B|)
  • dot(A, B) is the sum, over every word, of (count in first) multiplied by (count in second). A word missing from either string contributes 0.
  • |A| is the square root of the sum of the squared counts of first. |B| is the same for second.

Compute the result as dot / (norm_first * norm_second), with each norm computed separately as a square root. Do not round the result or clamp it, so tiny floating-point differences such as 0.9999999999999998 for identical strings are expected.

Edge case

If either string contains no words (it is empty or only whitespace), return 0.0.

Task

Implement the function that returns this score as a float.

Constraints

  • first and second are Python strings and may be empty.
  • Total length of the two strings is at most about 10^5 characters.
  • Words are separated by whitespace only. There is no lowercasing and no punctuation stripping.
  • The return value is a float between 0 and 1 inclusive, apart from floating-point error.

Examples

Example 1

Input: word_count_cosine('the cat sat on the mat', 'the cat sat on the mat')

Output: 0.9999999999999998

Example 2

Input: word_count_cosine('the cat sat', 'the dog sat')

Output: 0.6666666666666667

Example 3

Input: word_count_cosine('hello world', 'goodbye')

Output: 0

Example 4

Input: word_count_cosine('', 'any text')

Output: 0

Hints

Hint 1

Count how many times each whitespace-separated word appears in each string. A Counter (hash map from word to count) works well.

Hint 2

Only words present in both strings add anything to the dot product, and a Counter returns 0 for a missing key. The norms are square roots of the sums of squared counts.

Hint 3

Check for an empty word list before dividing, because a zero-length vector would cause a division by zero. Return 0.0 in that case.