KatInterview

Compute Compressed Vector Inner Product

Data Structure DesignAuto-graded · 14 test cases
MediumAuto-gradedData Structure Designarraysdesign-dshash-table

Last 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:

  1. "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 yields None (or null).
  2. "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.