789. Ad-click scoring: dot product of two hashed sparse vectors
An ad-click model uses the hashing trick: every feature (user country, ad id, hour of day, and so on) is hashed into one of millions of slots. A single request switches on only a few hundred slots, and the model's weight vector is stored sparsely too. Scoring a request is a dot product between two sparse vectors, and it runs for every ad on every page view, so it must only touch the non-zero entries.
Write sparse_dot(a, b). Each vector is a list of (index, value) pairs:
- indices are unique non-negative ints, sorted in increasing order,
- only non-zero values are stored,
- values can be ints or floats, positive or negative.
Return the sum of a_value * b_value over indices present in both. If no index is shared, or a list is empty, return 0.
Speed matters: both vectors can hold 100,000 entries, so comparing every pair (100,000 x 100,000 steps) is far too slow. Use the sorted order: walk both lists at once with two pointers, always advancing the one with the smaller index. That is about len(a) + len(b) steps.
def sparse_dot(a, b)Example 1
Input: sparse_dot([(0, 1), (3, 2), (5, 3)], [(3, 4), (5, 1), (9, 7)])
Output: 11 (2*4 + 3*1)
Example 2
Input: sparse_dot([], [(1, 5)])
Output: 0
Example 3
Input: a = [(1, 0.5)], b = [(1, 4.0)]
Output: 2.0
Constraints
- Up to 1,000,000 non-zero entries per vector.
- Indices are non-negative integers, unique and sorted.
Hint 1
Compare the current indices.
Hint 2
Advance the pointer with the smaller index.
Hint 3
Consider binary search when sizes are very different.
Common mistakes
- Converting to dense lists, which can be enormous.
- Advancing both pointers when indices differ.
- Assuming equal lengths.
Understand the idea
A sparse vector keeps only its non-zero entries. The dot product only gets contributions where both vectors are non-zero, so the work should scale with the number of stored entries, not the full dimension. With sorted pairs, a two-pointer merge finds the shared indices, the same idea as merging two sorted lists.