Compute Compressed Vector Inner Product
Data Structure DesignAuto-graded · 14 test casesLast updated
Process dynamic creation of compressed vectors and compute inner products using sparse representations.
Design an engine to manage and evaluate dot products for sparse vectors. A vector is sparse if most of its elements are equal to zero. Standard dense operations spend unnecessary work traversing zero components.
You are given a sequence of commands to execute. The commands are provided as two parallel lists: operations and arguments.
The supported operations are:
"create": Receives a list of integers[nums]representing a dense vector. Instantiate a new vector instance and assign it an implicit 0-based integer handle (0 for the first vector created, 1 for the second, and so on). This operation yieldsNone(ornull)."dot_product": Receives a list of two integer handles[v1_id, v2_id]. Compute the dot product between the two previously created vectors referenced by those handles. The dot product of two vectors $A$ and $B$ of length $n$ is defined as $\sum_{i=0}^{n-1} A[i] \times B[i]$. Returns the integer inner product value.
Return a list containing the output corresponding to each operation in the input sequence.
Constraints
- $1 \le \text{len}(operations) \le 1000$
- Each vector length $n$ satisfies $1 \le n \le 10^7$.
- The total count of non-zero values across all vector creation operations does not exceed $10^5$.
- Vector values fit within a standard signed 32-bit integer: $-10^4 \le \text{nums}[i] \le 10^4$.
- Arguments for
"dot_product"will always refer to existing, valid vector indices. - Vectors being multiplied are guaranteed to have matching dimensions.
Examples
Example 1
Input: sparse_vector_operations(['create', 'create', 'dot_product'], [[[1, 0, 0, 2, 3]], [[0, 3, 0, 4, 0]], [0, 1]])
Output: [None, None, 8]
Example 2
Input: sparse_vector_operations(['create', 'create', 'dot_product'], [[[0, 1, 0, 0, 0]], [[0, 0, 0, 0, 2]], [0, 1]])
Output: [None, None, 0]
Hints
Hint 1
Store only non-zero entries (index, value pairs) to save memory and skip zero terms during calculation.
Hint 2
A hash map mapping index -> non-zero value or two parallel sorted arrays allow fast matching.
Hint 3
When computing the dot product of two vectors, iterate over the elements of the smaller vector and check for matching indices in the larger vector.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
When vectors are sparse (containing mostly zeroes), scanning through every element to compute a dot product takes $O(n)$ time per dot product, where $n$ is the full vector length. When $n$ is large (up to $10^7$), this approach causes time-limit exceptions and wastes memory storing zeroes.
Instead, we extract and store only the non-zero indices and their values.
-
Vector Construction (
"create"):- Filter the dense vector array upon instantiation. Store non-zero entries as a key-value dictionary (or parallel lists of indices and values).
- Append the compressed vector to a list of vectors, retaining its position as its vector ID. Return
None.
-
Dot Product Calculation (
"dot_product"):- Retrieve the two vectors using their IDs.
- To optimize execution, identify which vector has fewer non-zero entries (
left). - Iterate through the key-value pairs of
left, checking if the corresponding index exists inright. - If present, multiply the values and accumulate the result into a running sum.
- Return the calculated total scalar product.
Complexity
- Creation Time: $O(n)$ where $n$ is the length of the vector, as we iterate through the input array once to filter out zeroes.
- Creation Space: $O(k)$ where $k$ is the number of non-zero elements in the vector.
- Dot Product Time: $O(\min(k_1, k_2))$ expected time using a hash map lookup, where $k_1, k_2$ are the non-zero counts of the two vectors.
- Dot Product Auxiliary Space: $O(1)$ extra space beyond the stored vectors.
Python Reference Solution
from typing import List, Optional
def sparse_vector_operations(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
vectors = []
results = []
for operation, args in zip(operations, arguments):
if operation == "create":
nums = args[0]
# Store only non-zero elements in a map: index -> value
vectors.append({i: value for i, value in enumerate(nums) if value != 0})
results.append(None)
elif operation == "dot_product":
first, second = args
left, right = vectors[first], vectors[second]
# Iterate through the vector with fewer non-zero terms
if len(left) > len(right):
left, right = right, left
total = sum(value * right.get(index, 0) for index, value in left.items())
results.append(total)
else:
raise ValueError("Unknown operation")
return results