KatInterview

Inner Product of Two Index-Value Lists

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssparse-vectorsorted-merge

Last updated

Compute the inner product of two sparse vectors given as sorted index-value pairs by intersecting their indices with a linear merge, without building dense arrays.

Sparse Vector Inner Product

A very long vector is stored compactly: only its nonzero positions are kept, as a list of [position, amount] pairs sorted by strictly increasing position. Any position that does not appear in the list holds the value 0.

You are given two such vectors, first and second, which describe vectors of the same (possibly huge) length. Return their inner product, which is the sum over all positions of the product of the two values at that position.

Do not expand either vector into a dense array. Positions are too large for that to be practical.

Details

  • Both lists are already sorted by position, so no sorting is needed.
  • Only positions that appear in both lists contribute to the result. A position missing from either list contributes 0.
  • A list may be empty. If either list is empty, or the two lists share no position, the answer is 0.
  • A stored amount may itself be 0. This is allowed and simply contributes 0.
  • The result may be negative or zero because of cancellation.
  • Your solution should remain efficient when one vector has far fewer entries than the other.

Constraints

  • Each vector has at most 200,000 stored pairs.
  • Positions are nonnegative 32-bit integers, unique within a vector.
  • Every stored amount is an integer in [-100000, 100000].
  • The absolute value of the answer is at most 2 * 10^15.

Examples

Example 1

Input: sparse_inner_product([[0, 1], [3, 2], [10, -4]], [[1, 7], [3, 5], [10, 2]])

Output: 2

Hints

Hint 1

A position that is missing from either vector contributes nothing, so the task is really about finding the positions common to both sorted lists.

Hint 2

Walk through both lists with one pointer each. Compare the current positions: if they are equal, add the product; otherwise move past the smaller one, since it cannot appear later in the other list.

Hint 3

Stop as soon as either pointer reaches the end of its list. Never create a dense array, since positions can be as large as about 2^31.