Multiply Two Sparse Feature Matrices Without Touching the Zeros
Last updated: November 29, 2026
Quick Overview
Given two sparse matrices A (m x k) and B (k x n), where most entries are zero, return their product A x B while skipping work on zero entries.
0
0
0 solved
Given two sparse matrices A (m x k) and B (k x n), where most entries are zero, return their product A x B while skipping work on zero entries.
A Google screen question tied to sparse feature matrices common in ranking and recommendation pipelines. The interviewer checks that you reorder the loops so zeros are skipped and that you can talk about CSR-style storage.
What the Interviewer Expects
- Writes the standard triple loop and explains its O(mkn) cost
- Reorders loops to iterate over nonzeros of A, then nonzeros of B's row
- Precomputes a compact nonzero list for B
- Discusses CSR / CSC formats
- Handles empty rows or all-zero inputs
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Both matrices are too large for memory; how would you distribute the multiply?
- Which storage format is best if you multiply by many different A matrices?
- Return the result itself in sparse form.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
Am x k,Bk x n as dense lists with mostly zeros. - Output: dense m x n product.
- Work should scale with the number of nonzero multiply pairs, not mkn....
High-Level Design
C[i][j] = sum over t of A[i][t] * B[t][j]. Reorder to i, t, j: for each nonzero A[i][t], add A[i][t] * B[t][j] into row i of C for each nonzero B[t][j]. Precompute, for every row t of B, t...