Dot Product of Two Sparse Vectors

Medium

Topics
ArrayHash TableTwo PointersDesign

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

a1001022334
b03040
non-zero in both, so it contributeszero, contributes nothing
The product sums 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.
The two vectors have equal length; the columns line up by index.
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

a0011020304
b00002
zero, contributes nothing
No column qualifies, so the answer is 0.
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

a00110203240506
b1000304
non-zero in both, so it contributeszero, contributes nothing
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

  1. 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.
  2. Set a cursor on each list.
  3. Compare the indices the cursors point at. If they are equal, add the product of the two values and advance both cursors.
  4. If they differ, advance the cursor on the smaller index — that entry has no partner and contributes nothing.
  5. 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 total
SensAI
Beta
Tap the mic to stop voice mode