← Questions

Dot product of two sparse vectors

0
MetaCodingLast asked Feb 2026

A coding interview question asked in Meta's technical phone screen, last asked Feb 2026. It tests hash maps, two pointers and sparse data.

Two vectors A and B have the same length n, which can be large (up to 10^5 or more), and most of their entries are zero. Store them compactly and compute their dot product, sum(A[i] * B[i]), in time proportional to the number of non-zero entries rather than n.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • SparseVector(nums: list[int]) — keeps only the non-zero entries.
  • dot_product(self, other: SparseVector) -> int — returns the dot product of the two vectors.

Example

A = [1, 0, 0, 2, 3]
B = [0, 3, 0, 4, 0]
A.dot_product(B)  ->  8      # only index 3 is non-zero in both: 2 * 4

A = [0, 0, 0]
B = [4, 5, 6]
A.dot_product(B)  ->  0

Constraints

  • 1 <= n <= 10^5; both vectors have the same length.
  • Values are integers and may be negative.

Clarifying questions

  • Are the vectors given densely, or already as (index, value) pairs sorted by index?
  • Is one vector much sparser than the other?
  • Will the same vector take part in many products?
  • Can the result overflow 32 bits?

What a strong answer covers

  • Two representations: a hash map from index to value, and a list of (index, value) pairs sorted by index.
  • With hash maps: iterate over the smaller map and look up each index in the other, O(min(nnz_A, nnz_B)) expected.
  • With sorted pairs: a two-pointer merge, O(nnz_A + nnz_B), cache friendly and with no hashing.
  • When one vector is far sparser: binary search the denser list for each index of the sparser one, O(nnz_small * log nnz_large).
  • Reusing work: build the compact form once and reuse it across many products.
  • Tests: no overlap, one all-zero vector, negative values, identical vectors.

Follow-ups

  • One vector has 10 non-zeros and the other has 10^6. Which approach do you pick?
  • Compute the product of a sparse matrix and a sparse vector.
  • The vectors are too large for one machine. How do you compute the dot product?

Where it's asked

  • Meta · Technical phone screen · Last asked Feb 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

hash maps · two pointers · sparse data

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding