KatInterview

Compute Dot Products for Memory-Efficient Integer Vectors

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designhash-mapsparse-dataoptimization

Last 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, where vectors[i] represents the i-th vector
  • operations: a list of operation names (strings)
  • arguments: a list of argument pairs, where arguments[j] = [left, right] specifies two vector indices

For each operation:

  • If the operation is "dotProduct", compute the dot product of vectors[left] and vectors[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