Sparse Matrix Implementation with Operations
Data Structure DesignModel answerLast updated
Build a memory-efficient representation for sparse matrices and implement addition, multiplication, and display operations.
You're building a component for an analytics platform that works with very large matrices containing mostly zeros (sparse matrices). For example, a 1,000,000 × 1,000,000 matrix might have only a few million non-zero entries out of a trillion possible cells.
Design a data structure to represent sparse matrices efficiently and implement three operations:
print()– Display the matrix contentsadd(A, B)– Return the sum of two matricesmultiply(A, B)– Return the product of two matrices
For each operation, explain the time and space complexity in terms of the number of non-zero entries (nnz) and matrix dimensions.
Constraints:
- Matrices can be up to 10⁶ × 10⁶ in dimension
- Only a small fraction of entries are non-zero
- Values are numeric (integers or floats)
- Standard matrix operation rules apply (dimension matching for add, inner dimension matching for multiply)
What to deliver:
- Data structure design with justification
- Implementation of all three operations
- Complexity analysis
- Discussion of design tradeoffs
Hints
Hint 1
Consider storing only non-zero values instead of the full grid
Hint 2
Indexing by rows enables efficient iteration during multiplication
Hint 3
Think about how matrix multiplication accesses data: which entries do you actually need to visit?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarifying Questions
Before implementing, I'd confirm:
- Scale: What are typical dimensions and sparsity levels? This determines whether dense storage (O(rows × cols)) is even feasible
- Output format: For
print(), should we show a dense grid (only practical for small matrices) or list non-zero entries? - Mutability: Will matrices be modified frequently or built once and queried many times?
- Zero handling: Should we explicitly store zeros that result from operations like
5 + (-5)?
For this solution, I'll assume 10⁶ × 10⁶ matrices with millions of non-zeros, making dense storage impractical.
Data Structure: Dictionary of Rows
I'll use a two-level dictionary structure: data[row][col] = value, storing only non-zero entries.
Why this works:
- Memory scales with non-zeros, not dimensions: O(nnz) instead of O(rows × cols)
- O(1) average-case lookup and insertion
- Natural iteration over a row's non-zeros, which matrix multiplication requires
- Simple to implement and reason about
Alternative: Compressed Sparse Row (CSR)
CSR uses three arrays: values, column indices, and row pointers. It's more memory-compact and cache-friendly, making it ideal for production systems doing heavy multiplication. The tradeoff is that insertions are expensive (O(nnz) to shift elements). A practical approach: use dictionary-of-rows for construction, convert to CSR for repeated read-only operations.
Operations
Addition: Merge the two matrices. Copy A's entries, then iterate through B's entries, adding values where keys match. Remove any resulting exact zeros.
Multiplication: Use row-based accumulation. For each non-zero A[i][k], iterate over row k of B, accumulating A[i][k] × B[k][j] into result[i][j]. This avoids visiting zeros in A or unreferenced rows in B.
The key insight: traditional multiplication computes each output cell as a dot product of a row and column, visiting all R×C positions. The row-based approach only visits non-zero entries of A and their corresponding rows in B.
Print: For large matrices, output non-zero triples (row, col, value) sorted by position. For small matrices, optionally support dense grid format.
Complexity Analysis
Let R, C be dimensions and nnz(X) be the count of non-zeros in matrix X.
| Operation | Time | Space |
|---|---|---|
| get/set cell | O(1) average | O(1) |
| add(A, B) | O(nnz(A) + nnz(B)) | O(nnz(result)) |
| multiply(A, B) | O(nnz(A) × avg_nnz_per_row(B)) | O(nnz(result)) |
| print sparse | O(nnz log nnz) sorted | O(nnz) |
Multiplication detail: The time is exactly the number of scalar multiplications performed. For each non-zero A[i][k], we process nnz(B row k) entries. With uniform sparsity, this approximates nnz(A) × nnz(B) / B.rows.
Edge Cases
- Dimension mismatch: Addition requires identical shapes; multiplication requires A.cols = B.rows. Validate and raise errors.
- Zero assignment: Setting a cell to zero must delete the entry, not store it
- Cancellation: 3 + (-3) or other operations producing exact zero should not leave explicit zero entries
- Empty matrices/rows: Loops handle these naturally by iterating over nothing
- Floating point zeros: For this problem, exact equality checks are acceptable
Implementation
from collections import defaultdict
class SparseMatrix:
def __init__(self, rows, cols, entries=None):
if rows <= 0 or cols <= 0:
raise ValueError("dimensions must be positive")
self.rows = rows
self.cols = cols
self.data = {} # data[r][c] = value
if entries:
for r, c, val in entries:
self.set(r, c, val)
def _validate_index(self, r, c):
if not (0 <= r < self.rows and 0 <= c < self.cols):
raise IndexError(f"index ({r},{c}) out of bounds")
def get(self, r, c):
self._validate_index(r, c)
return self.data.get(r, {}).get(c, 0)
def set(self, r, c, val):
self._validate_index(r, c)
if val == 0:
if r in self.data:
self.data[r].pop(c, None)
if not self.data[r]:
del self.data[r]
else:
if r not in self.data:
self.data[r] = {}
self.data[r][c] = val
def nnz(self):
return sum(len(row) for row in self.data.values())
def print(self, dense=False):
if dense and self.rows * self.cols > 10000:
print("Matrix too large for dense display")
return
if dense:
for r in range(self.rows):
row_data = self.data.get(r, {})
print(" ".join(str(row_data.get(c, 0)) for c in range(self.cols)))
else:
print(f"{self.rows}×{self.cols} sparse matrix, {self.nnz()} non-zeros:")
for r in sorted(self.data.keys()):
for c in sorted(self.data[r].keys()):
print(f" [{r},{c}] = {self.data[r][c]}")
def add(A, B):
if A.rows != B.rows or A.cols != B.cols:
raise ValueError("matrices must have same dimensions for addition")
result = SparseMatrix(A.rows, A.cols)
# Copy A's entries
for r, row in A.data.items():
result.data[r] = dict(row)
# Add B's entries
for r, row_b in B.data.items():
if r not in result.data:
result.data[r] = {}
for c, val_b in row_b.items():
sum_val = result.data[r].get(c, 0) + val_b
if sum_val == 0:
result.data[r].pop(c, None)
else:
result.data[r][c] = sum_val
if not result.data[r]:
del result.data[r]
return result
def multiply(A, B):
if A.cols != B.rows:
raise ValueError("inner dimensions must match for multiplication")
result = SparseMatrix(A.rows, B.cols)
for i, row_a in A.data.items():
accumulator = defaultdict(float)
# For each non-zero in row i of A
for k, val_a in row_a.items():
# Multiply by row k of B
if k in B.data:
for j, val_b in B.data[k].items():
accumulator[j] += val_a * val_b
# Store non-zero results
result.data[i] = {j: v for j, v in accumulator.items() if v != 0}
if not result.data[i]:
del result.data[i]
return result
Common Mistakes
- Storing explicit zeros: Defeats the purpose of sparse representation
- Column-major access in multiplication: Iterating over columns of B is inefficient without a column index
- Visiting all R×C positions: The whole point is to skip zeros
- Not validating dimensions: Dimension mismatches produce incorrect results silently
- Using dense intermediate storage: Even temporary O(R×C) buffers can exhaust memory