Dot Product of Two Sparse Vectors
Medium
Topics
Two vectors a and b of equal length are sparse: most of their entries are zero. Return their dot product, which is the sum of a[i] * b[i] over every index.
The point of the exercise is to spend time proportional to the non-zero entries rather than to the vector length, since a sparse vector of length a million may hold only a handful of values.
LeetCode poses this as a SparseVector class whose constructor compresses the input and whose dotProduct takes another instance. The judge here passes both vectors to one function; the compression you would store in the constructor is the first thing to build.
Example 1
a[i] × b[i] down the columns, and a column contributes only when both entries are non-zero — which is 1 of the 5 columns here. That gives 2×4 = 8.Input: a = [1,0,0,2,3], b = [0,3,0,4,0] Output: 8 Explanation: Only index 3 has a non-zero in both vectors: 2 * 4.
Example 2
Input: a = [0,1,0,0,0], b = [0,0,0,0,2] Output: 0 Explanation: The vectors never have a non-zero at the same index.
Example 3
Input: a = [0,1,0,0,2,0,0], b = [1,0,0,0,3,0,4] Output: 6 Explanation: Index 4 is the only overlap: 2 * 3.
Constraints
- n == a.length == b.length
- 1 <= n <= 10^5
- 0 <= a[i], b[i] <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
The straight loop over every index is correct and gives the right answer, but it reads a million entries to multiply six of them. The interesting question is what to store so that the zeros are never touched.
A product contributes only when both factors are non-zero, so the work is bounded not by either vector’s length but by the overlap of their non-zero positions. Storing each vector as a list of (index, value) pairs, in increasing index order, makes that overlap findable by advancing two cursors — the same merge step as intersecting two sorted lists.
A hash map of index to value is the other natural store, and it is worth knowing why the sorted pairs are usually preferred: the map costs a hash lookup per entry of the other vector, so it is only a win when one vector is far sparser than the other. The two-cursor merge is proportional to the sum of the two non-zero counts either way, with no hashing.
Approach
- Compress each vector into a list of
(index, value)pairs for its non-zero entries, in increasing index order. This is the step LeetCode’s constructor would do once per vector. - Set a cursor on each list.
- Compare the indices the cursors point at. If they are equal, add the product of the two values and advance both cursors.
- If they differ, advance the cursor on the smaller index — that entry has no partner and contributes nothing.
- Stop when either list is exhausted; everything left over has no partner either.
Walkthrough
a = [1,0,0,2,3]
b = [0,3,0,4,0]
compressed
a -> (0,1) (3,2) (4,3)
b -> (1,3) (3,4)
cursors compare action
(0,1) (1,3) 0 < 1 advance a
(3,2) (1,3) 3 > 1 advance b
(3,2) (3,4) equal add 2*4 = 8, advance both
(4,3) -- b done stop
answer 8
Five index pairs existed; three were examined.Complexity
- Time — O(na + nb): after compression the merge advances at least one cursor per step, so it runs in the number of non-zero entries, not the vector length. Building the compressed form is one O(n) pass per vector — in the class framing that happens once in the constructor and is amortised over every later dot product.
- Space — O(na + nb): one pair per non-zero entry.
Common Pitfalls
- Storing the compressed pairs unsorted, or in a set. The merge depends on both lists being in increasing index order.
- Advancing both cursors when the indices differ. That skips an entry that might have matched the other list further along.
- Treating the zeros as worth storing. A pair with value zero contributes nothing and reintroduces the cost the compression removes.
- Overflow in a language with fixed-width integers. With 10^5 entries at 100 each the dot product reaches 10^9, which still fits a signed 32-bit integer but leaves little headroom.
Full Solution — all languages
class Solution:
def dotProduct(self, a, b):
pa = [(i, v) for i, v in enumerate(a) if v != 0]
pb = [(i, v) for i, v in enumerate(b) if v != 0]
total = 0
i = j = 0
while i < len(pa) and j < len(pb):
ia, va = pa[i]
ib, vb = pb[j]
if ia == ib:
total += va * vb
i += 1
j += 1
elif ia < ib:
i += 1
else:
j += 1
return totalimport java.util.*;
class Solution {
public int dotProduct(int[] a, int[] b) {
List<int[]> pa = new ArrayList<>(), pb = new ArrayList<>();
for (int i = 0; i < a.length; i++) if (a[i] != 0) pa.add(new int[]{i, a[i]});
for (int i = 0; i < b.length; i++) if (b[i] != 0) pb.add(new int[]{i, b[i]});
long total = 0;
int i = 0, j = 0;
while (i < pa.size() && j < pb.size()) {
int[] x = pa.get(i), y = pb.get(j);
if (x[0] == y[0]) {
total += (long) x[1] * y[1];
i++;
j++;
} else if (x[0] < y[0]) i++;
else j++;
}
return (int) total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int dotProduct(vector<int>& a, vector<int>& b) {
vector<pair<int, int>> pa, pb;
for (size_t i = 0; i < a.size(); i++) if (a[i] != 0) pa.push_back({(int)i, a[i]});
for (size_t i = 0; i < b.size(); i++) if (b[i] != 0) pb.push_back({(int)i, b[i]});
long long total = 0;
size_t i = 0, j = 0;
while (i < pa.size() && j < pb.size()) {
if (pa[i].first == pb[j].first) {
total += (long long)pa[i].second * pb[j].second;
i++;
j++;
} else if (pa[i].first < pb[j].first) i++;
else j++;
}
return (int)total;
}
};/**
* @param {number[]} a
* @param {number[]} b
* @return {number}
*/ var dotProduct = function(a, b) {
const pa = [], pb = [];
for (let i = 0; i < a.length; i++) if (a[i] !== 0) pa.push([i, a[i]]);
for (let i = 0; i < b.length; i++) if (b[i] !== 0) pb.push([i, b[i]]);
let total = 0, i = 0, j = 0;
while (i < pa.length && j < pb.length) {
if (pa[i][0] === pb[j][0]) {
total += pa[i][1] * pb[j][1];
i++;
j++;
} else if (pa[i][0] < pb[j][0]) i++;
else j++;
}
return total;
};