Skip to content

Commit 2928b82

Browse files
Sparse Matrix Multiplication: Accepted
1 parent e736b60 commit 2928b82

2 files changed

Lines changed: 81 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ My accepted leetcode solutions to some of the common interview problems.
2323
- [Find the Celebrity](problems/src/array/FindTheCelebrity.java) (Medium)
2424
- [Meeting Rooms](problems/src/array/MeetingRooms.java) (Easy)
2525
- [Longest Continuous Increasing Subsequence](problems/src/array/LongestIncreasingSubsequence.java) (Easy)
26+
- [Sparse Matrix Multiplication](problems/src/array/SparseMatrixMultiplication.java) (Medium)
2627

2728
#### [Backtracking](problems/src/backtracking)
2829

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package array;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 03/12/2017.
5+
*
6+
* Given two sparse matrices A and B, return the result of AB.
7+
8+
You may assume that A's column number is equal to B's row number.
9+
10+
Example:
11+
12+
A = [
13+
[ 1, 0, 0],
14+
[-1, 0, 3]
15+
]
16+
17+
B = [
18+
[ 7, 0, 0 ],
19+
[ 0, 0, 0 ],
20+
[ 0, 0, 1 ]
21+
]
22+
23+
24+
| 1 0 0 | | 7 0 0 | | 7 0 0 |
25+
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
26+
| 0 0 1 |
27+
28+
Solution: Skip the rows and columns which you already know would result in zero after multiplication.
29+
*/
30+
public class SparseMatrixMultiplication {
31+
32+
/**
33+
* Main method
34+
* @param args
35+
* @throws Exception
36+
*/
37+
public static void main(String[] args) throws Exception{
38+
int[][] A = {{1,0,0,1}};
39+
int[][] B = {{7,0,0}, {0,0,0}, {0,0,1}, {0,0,1}};
40+
int[][] C = new SparseMatrixMultiplication().multiply(A, B);
41+
}
42+
43+
public int[][] multiply(int[][] A, int[][] B) {
44+
boolean[] AH = new boolean[A.length]; // Metadata for matrix A
45+
boolean[] BH = new boolean[B[0].length]; // Metadata for matrix A
46+
for(int i = 0; i < A.length; i ++){
47+
for(int j = 0; j < A[0].length; j ++){
48+
if(A[i][j] != 0){
49+
AH[i] = true;
50+
break;
51+
}
52+
}
53+
}
54+
55+
for(int i = 0; i < B[0].length; i ++){
56+
for(int j = 0; j < B.length; j ++){
57+
if(B[j][i] != 0){
58+
BH[i] = true;
59+
break;
60+
}
61+
}
62+
}
63+
64+
int[][] C = new int[A.length][B[0].length];
65+
for(int i = 0; i < C.length; i ++){
66+
if(AH[i]){
67+
for(int j = 0; j < C[0].length; j++){
68+
if(BH[j]){
69+
int sum = 0;
70+
for(int k = 0; k < A[0].length; k++){
71+
sum += A[i][k] * B[k][j];
72+
}
73+
C[i][j] = sum;
74+
}
75+
}
76+
}
77+
}
78+
return C;
79+
}
80+
}

0 commit comments

Comments
 (0)