Product of Two Mostly-Zero Grids
Arrays & HashingAuto-graded · 20 test casesLast 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
rrows andwcolumns, 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.
leftisr x candrightisc 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 * wmultiplications.
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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The definition of the product is C[i][j] = sum over t of left[i][t] * right[t][j]. Any term where either factor is zero adds nothing, so only terms where both left[i][t] and right[t][j] are nonzero matter.
- Compress
rightby rows. For each rowt, store a list of(column, value)pairs for its nonzero entries. - Allocate the result as an
r x wgrid of zeros. The shape comes fromlen(left)andlen(right[0]). - Scan
leftrow by row. For each nonzeroleft[i][t], walk the stored pairs ofright's rowtand addleft[i][t] * valueintoresult[i][column].
Why it is correct
The loops visit exactly the pairs (i, t) with left[i][t] != 0, and for each of them exactly the columns j with right[t][j] != 0. Each surviving term is added to its cell exactly once, and all dropped terms were zero. Since the result starts at zero and addition is order-independent, every cell ends with its full dot product. Cancellations (for example 2*3 + (-6)*1) naturally give 0. Testing with != 0 rather than > 0 handles negative values.
Complexity
Let F be the number of multiplications where both operands are nonzero.
- Time:
O(r*c + c*w + F), plusO(r*w)to allocate the output. In the dense worst caseF = r*c*w, which matches the naive method. - Space:
O(r*w)for the required output, plusO(c + nnz(right))for the compressed rows.
Reference solution
from typing import List
def sparse_grid_product(left: List[List[int]], right: List[List[int]]) -> List[List[int]]:
r = len(left)
w = len(right[0])
# For each row of `right`, keep only (column, value) pairs that are nonzero.
right_nonzero = []
for row in right:
right_nonzero.append([(j, v) for j, v in enumerate(row) if v != 0])
result = [[0] * w for _ in range(r)]
for i, row in enumerate(left):
out_row = result[i]
for t, a in enumerate(row):
if a == 0:
continue
for j, b in right_nonzero[t]:
out_row[j] += a * b
return result