Problem · Array

Sparse Vector Dot Product from Tuples

Learn this problem
EasyMeta logoMetaFULLTIMEONSITE INTERVIEW
See Meta hiring insights

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

Examples

Example 1

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

Only 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 = -11

The shared indices contribute -2 * 3 + 5 * -1 = -11.

Example 3

length = 6first = []second = [[2,9]]return = 0

The 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^9 and 10^9, inclusive.
  • The final dot product fits a signed 64-bit integer.

More Meta problems

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