Problem · Array
Sparse Vector Dot Product from Tuples
Learn this problemProblem statement
Two equal-length integer vectors are stored only by their nonzero entries. Each row [index, value] in first or second represents one nonzero value at that zero-based index.
Both tuple arrays use strictly increasing, unique, in-range indices. Compute and return the vectors' dot product as a signed 64-bit integer. Indices missing from a tuple array have value zero.
The vector length length establishes the shared dimension and may be zero.
Function
sparseDotProduct(length: int, first: int[][], second: int[][]) → longExamples
Example 1
length = 5first = [[0,1],[3,2],[4,3]]second = [[1,3],[3,4]]return = 8Only index 3 appears in both vectors, contributing 2 * 4 = 8.
Example 2
length = 4first = [[1,-2],[3,5]]second = [[0,7],[1,3],[3,-1]]return = -11The shared indices contribute -2 * 3 + 5 * -1 = -11.
Example 3
length = 6first = []second = [[2,9]]return = 0The first vector is all zero, so the dot product is zero.
Constraints
0 <= length <= 10^9.0 <= first.length, second.length <= 200000.- Every tuple contains exactly
[index, value]. - Within each operand, indices are unique, strictly increasing, and satisfy
0 <= index < length. - Every stored value is nonzero and lies between
-10^9and10^9, inclusive. - The final dot product fits a signed 64-bit integer.