KatInterview

Product of Two Mostly-Zero Grids

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingmatrixsparsesimulation

Last updated

Compute the product of two mostly-zero integer matrices by precomputing nonzero positions so that no work is spent on zero operands.

Product of Two Mostly-Zero Grids

You are given two rectangular grids of integers, left and right. Most of the entries in each grid are expected to be zero. Your task is to return their matrix product as a full (dense) grid.

If left has r rows and c columns, then right has exactly c rows and some number w of columns. The product has r rows and w columns, and the entry in row i, column j is the sum over all t from 0 to c - 1 of left[i][t] * right[t][j].

Because the inputs are mostly zeros, a straightforward triple loop does a lot of pointless work. Your solution should be designed so that it only multiplies pairs of values where both are nonzero, for example by recording the positions of the nonzero entries ahead of time.

Requirements

  • Return the product as a list of lists with r rows and w columns, including zeros where appropriate.
  • The shape of the result is determined only by the shapes of the inputs, never by where the nonzero values happen to be. An all-zero input still produces a zero grid of the full size.
  • Entries may be negative, and partial products may cancel each other out to give 0.

Constraints

  • 1 <= r, c, w <= 500
  • All entries are integers.
  • left is r x c and right is c x w; both are non-empty.
  • Aim for a running time that depends on the number of nonzero entries involved, rather than always performing r * c * w multiplications.

Examples

Example 1

Input: sparse_grid_product([[1, 0, 0], [-1, 0, 3]], [[7, 0, 0], [0, 0, 0], [0, 0, 1]])

Output: [[7, 0, 0], [-7, 0, 3]]

Example 2

Input: sparse_grid_product([[1, 2], [3, 4]], [[5, 6], [7, 8]])

Output: [[19, 22], [43, 50]]

Example 3

Input: sparse_grid_product([[0, 0], [0, 0]], [[1, 2], [3, 4]])

Output: [[0, 0], [0, 0]]

Hints

Hint 1

Any term in the sum where either factor is zero contributes nothing, so it can be skipped entirely.

Hint 2

Preprocess each row of the right grid into a list of (column, value) pairs holding only its nonzero entries.

Hint 3

Loop over left[i][t]; if nonzero, add left[i][t] * value to result[i][column] for each stored pair in right's row t. Build the result with shape r x w up front.