Problem · Array
Sparse Vector Dot Product
Learn this problemProblem statement
Given two equal-length arrays first and second, treat each as a vector of signed integers. Conceptually construct a sparse representation that stores only nonzero index-value pairs, then return their dot product as a signed 64-bit integer.
The dot product is the sum of first[i] * second[i] over all indices. Zero entries do not need explicit storage.
Function
sparseDotProduct(first: int[], second: int[]) → longExamples
Example 1
first = [1,0,0,2,3]second = [0,3,0,4,0]return = 8Only index 3 is nonzero in both vectors, contributing 2 * 4 = 8.
Example 2
first = [0,-2,0,5]second = [7,3,0,-1]return = -11The shared nonzero indices contribute -2 * 3 + 5 * -1 = -11.
Constraints
0 <= first.length == second.length <= 200000.-10^6 <= first[i], second[i] <= 10^6.- The final dot product fits a signed 64-bit integer.