Inner Product of Two Index-Value Lists
Arrays & HashingAuto-graded · 17 test casesLast 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 contributes0. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A position contributes to the inner product only if it is stored in both vectors, because a missing position holds 0 and makes the product 0. So the task reduces to intersecting two sorted lists of positions and summing the products of the amounts at the shared positions.
Use two pointers, i into first and j into second:
- If the positions at both pointers are equal, add the product of their amounts and advance both pointers.
- If
first's position is smaller, it cannot occur anywhere later insecond(those positions are all at least as large as the current one insecond), so advancei. - Otherwise, advance
jby the symmetric argument. - Stop when either list is exhausted, since the leftover entries of the other list have no partner.
Why it is correct
The invariant is that every matching pair of positions before (i, j) has been added exactly once and none has been skipped. Positions are unique within each vector, so a matched entry cannot match anything else, and advancing both pointers is safe. Discarding the smaller position is safe because of sortedness. Each iteration advances at least one pointer, so the loop terminates. Every skipped entry would have contributed 0, so the total equals the inner product.
Positions are only compared, never used as array indices, so large values need no special handling. Empty inputs, disjoint inputs, stored zeros and cancellation all fall out naturally and return the right value. Python integers are arbitrary precision, so overflow is not an issue.
Complexity
- Time: O(m + n), where m and n are the numbers of stored pairs.
- Space: O(1) extra.
When one list is much shorter, you could instead binary-search (or gallop) through the longer list for each entry of the shorter one, giving about O(m log(n/m)). The plain linear merge is the simplest correct approach and is fast enough here.
Reference solution
from typing import List
def sparse_inner_product(first: List[List[int]], second: List[List[int]]) -> int:
i = j = total = 0
n, m = len(first), len(second)
while i < n and j < m:
pi = first[i][0]
pj = second[j][0]
if pi == pj:
total += first[i][1] * second[j][1]
i += 1
j += 1
elif pi < pj:
i += 1
else:
j += 1
return total