Dot Product of Two Sparse Embedding Vectors Stored Compactly
Last updated: November 29, 2026
Quick Overview
Design a SparseVector class that stores only non-zero entries of a very long vector and computes the dot product with another SparseVector efficiently.
0
0
0 solved
Design a SparseVector class that stores only non-zero entries of a very long vector and computes the dot product with another SparseVector efficiently.
Common at Google in a technical screen, framed around sparse feature vectors in ads or search ranking models where most features are zero. The interviewer checks your choice between a hash map and a sorted list of (index, value) pairs and how you handle very different sparsity levels.
What the Interviewer Expects
- Stores only non-zero entries
- Compares hash map and sorted index list representations
- Iterates over the sparser vector when using a map
- Implements a two-pointer merge for sorted pairs
- Discusses the case where one vector is dense and the other very sparse
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- One vector has 10 non-zeros, the other has 10 million; what is fastest?
- How would you compute cosine similarity between many sparse vectors?
- How would you store these vectors on disk for fast batch scoring?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
SparseVector(nums)builds from a dense list.dot(other)returns the dot product.- Vectors can have length in the millions with only a handful of non-zeros.
- Both vectors have the same length...
High-Level Design
Two reasonable representations:
- Hash map index to value. Dot product iterates over the smaller map and looks up indices in the other: O(min(a, b)) expected.
- Sorted list of (index, value) pairs....