Compute Dot Products for Memory-Efficient Integer Vectors
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests efficient sparse data representation using hash maps and optimizing operations by focusing on non-zero elements only.
You are given a collection of integer vectors where most elements are zero. Your task is to compute dot products between pairs of these vectors efficiently.
You receive three inputs:
vectors: a list of integer arrays, wherevectors[i]represents thei-th vectoroperations: a list of operation names (strings)arguments: a list of argument pairs, wherearguments[j] = [left, right]specifies two vector indices
For each operation:
- If the operation is
"dotProduct", compute the dot product ofvectors[left]andvectors[right] - For any other operation name, output
None
The dot product of two vectors a and b of the same length is:
a · b = a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1]
Return a list of results corresponding to each operation in order.
Important: Vectors can be very long (up to 10⁵ elements) but typically contain only a small number of non-zero values. Your solution should take advantage of this sparsity—both in memory usage when storing vectors and in computation time when calculating dot products.
Constraints
- 1 ≤ len(vectors) ≤ 100
- All vectors in the input have the same length
- 0 ≤ vector length ≤ 10⁵
- -1000 ≤ vector elements ≤ 1000
- 1 ≤ len(operations) ≤ 1000
- len(operations) == len(arguments)
- 0 ≤ left, right < len(vectors)
- Vectors may contain negative values; only exact zeros should be considered "sparse"
Examples
Example 1
Input: compute_sparse_dot_products([[1, 0, 0, 2, 3], [0, 3, 0, 4, 0]], ['dotProduct'], [[0, 1]])
Output: [8]
Example 2
Input: compute_sparse_dot_products([[0, 1, 0, 0, 2], [1, 0, 0, 0, 3], [0, 0, 4]], ['dotProduct', 'dotProduct'], [[0, 1], [1, 2]])
Output: [6, 0]
Hints
Hint 1
Store only the positions and values where elements are non-zero instead of keeping the full vector
Hint 2
When computing a dot product, you only need to examine positions where both vectors have non-zero values
Hint 3
Iterating through the vector with fewer non-zero elements and looking up those positions in the other vector minimizes work
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The central insight is that in a dot product, any position where either vector has a zero contributes nothing to the final sum. Therefore, we only need to examine positions where both vectors are non-zero.
Sparse Representation: Instead of storing all elements, represent each vector as a hash map (dictionary) that maps each index to its non-zero value. This reduces space from O(n) to O(k), where k is the count of non-zero elements.
Efficient Dot Product Computation:
- Convert both input vectors to their sparse representations (if not already done)
- Choose the vector with fewer non-zero entries
- Iterate through each non-zero position in the smaller vector
- Look up that same position in the other vector's map (defaulting to 0 if absent)
- Multiply the values and accumulate the sum
This strategy ensures we perform at most min(k_a, k_b) multiplications rather than examining all n positions.
Why It Works
The dot product is defined as the sum over all indices. We can partition these indices into two groups:
- Indices where the first vector is zero: these contribute 0 to the sum
- Indices where the first vector is non-zero: we look these up in the second vector
By iterating only over non-zero indices from the first vector and using dict.get(index, 0) on the second, we capture all non-zero contributions while automatically treating missing indices as zero. The result is mathematically identical to the full summation.
Choosing the smaller map to iterate means we minimize the number of dictionary lookups, giving us O(min(k_a, k_b)) time instead of O(max(k_a, k_b)).
Complexity
Time:
- Building the sparse representations: O(N) where N is the total number of elements across all input vectors (we must examine each element once)
- Each dot product query: O(min(k_left, k_right)) expected time, where k is the number of non-zero elements in each vector
Space:
- O(K) total where K is the sum of all non-zero elements across all vectors
- Each dot product uses O(1) additional space
When vectors are truly sparse (k << n), this is dramatically faster than the naive O(n) approach for each dot product.
from typing import List, Optional
def compute_sparse_dot_products(vectors: List[List[int]], operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
# Convert each vector to a sparse representation: map from index to non-zero value
sparse = [{i: val for i, val in enumerate(vec) if val != 0} for vec in vectors]
results = []
for op, args in zip(operations, arguments):
if op == "dotProduct":
left_idx, right_idx = args
left_map, right_map = sparse[left_idx], sparse[right_idx]
# Iterate over the smaller map for efficiency
if len(left_map) > len(right_map):
left_map, right_map = right_map, left_map
dot_product = sum(val * right_map.get(idx, 0) for idx, val in left_map.items())
results.append(dot_product)
else:
results.append(None)
return results