Dot Product of Two Sparse Vectors

Implement dot product for vectors with mostly zero entries — store only non-zero indices.

Medium
Time O(nnz1 + nnz2) Space O(nnz)
LeetCode
4 min read
hash-map design two-pointer

Problem#

Implement SparseVector from a dense vector and compute dot products efficiently when most entries are zero.

Examples#

  • v1 = [1,0,0,2,3], v2 = [0,3,0,4,0], dot(v1, v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8.
  • v1 = [0,1,0,0,0], v2 = [0,0,0,0,2], dot = 0.

Constraints#

  • n <= 10^5. Non-zero counts can be small.

Hints#

Hint
Store sorted (index, value) pairs; on dot, march two pointers along each side.

Approach#

Store non-zero entries as sorted vector<pair<int,int>>. On dot, use two pointers; advance whichever index is smaller, and on equality multiply and advance both.

Solution#

Dot Product of Two Sparse Vectors
class SparseVector {
vector<pair<int,int>> data; // (index, value), sorted by index
public:
SparseVector(vector<int>& nums) {
for (int i = 0; i < (int)nums.size(); ++i)
if (nums[i] != 0) data.emplace_back(i, nums[i]);
}
int dotProduct(SparseVector& vec) {
int i = 0, j = 0, ans = 0;
auto& A = data;
auto& B = vec.data;
while (i < (int)A.size() && j < (int)B.size()) {
if (A[i].first == B[j].first) { ans += A[i].second * B[j].second; ++i; ++j; }
else if (A[i].first < B[j].first) ++i;
else ++j;
}
return ans;
}
};

Editorial#

For two sparse vectors with non-zero counts k1, k2, two-pointer dot product runs in O(k1 + k2) — strictly better than scanning the dense form when both are sparse. If one vector is dense and the other sparse, iterating only the sparse one’s entries and indexing into the dense one is even faster.

Complexity#

  • Time: O(k1 + k2).
  • Space: O(nnz).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.