v9.1.1
Menu

Dot Product of Two Sparse Vectors

easyPROHash Maps & DesignMeta DSA

Given two sparse vectors represented as arrays, compute their dot product efficiently.

A sparse vector has mostly zero elements. Store only non-zero elements for efficiency.

Example

Input
1,0,0,2,3
0,3,0,4,0
Output
8
Reasoning
  • The inputs are two vectors of the same length 5: a=[1,0,0,2,3]a = [1, 0, 0, 2, 3] and b=[0,3,0,4,0]b = [0, 3, 0, 4, 0]. Most entries are zero, which is what makes them sparse.
  • The dot product is a⋅b=∑iaibia \cdot b = \sum_i a_i b_i, one product per position.
  • A position contributes something only when both entries are non-zero. aa is non-zero at positions 0, 3 and 4; bb is non-zero at positions 1 and 3. The only shared position is 3.
  • Every other term vanishes: at position 0, 1⋅0=01 \cdot 0 = 0; at position 1, 0⋅3=00 \cdot 3 = 0; at position 4, 3⋅0=03 \cdot 0 = 0.
  • So a⋅b=2⋅4=8a \cdot b = 2 \cdot 4 = 8, a single integer, which is the output 8.
  • Notice that if the two vectors had no non-zero position in common, the answer would be 00 no matter how large their values were.

Constraints

  • 1 <= len(nums1) == len(nums2) <= 10^5
  • 0 <= nums[i] <= 100

Learn this in

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.