Problem · Array

Sparse Vector Dot Product

Learn this problem
MediumAnduril logoAndurilFULLTIMEPHONE SCREEN

Problem 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[]) → long

Examples

Example 1

first = [1,0,0,2,3]second = [0,3,0,4,0]return = 8

Only index 3 is nonzero in both vectors, contributing 2 * 4 = 8.

Example 2

first = [0,-2,0,5]second = [7,3,0,-1]return = -11

The 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.

More Anduril problems

drafts saved locally
public long sparseDotProduct(int[] first, int[] second) {
    // Write your code here.
}
first[1,0,0,2,3]
second[0,3,0,4,0]
expected8
checking account