Skip to content

Commit e93dad7

Browse files
docs: explain Strassen algorithm complexity
1 parent 3c88735 commit e93dad7

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

divide_and_conquer/strassen_matrix_multiplication.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,21 @@ def print_matrix(matrix: list) -> None:
7474
def actual_strassen(matrix_a: list, matrix_b: list) -> list:
7575
"""
7676
Recursive function to calculate the product of two matrices, using the Strassen
77-
Algorithm. It only supports square matrices of any size that is a power of 2.
77+
Algorithm.
78+
79+
Time complexity:
80+
The recurrence is T(n) = 7 T(n/2) + \u0398(n^2), which solves to
81+
T(n) = \u0398(n^{log_2 7}) \u2248 \u0398(n^{2.8074}). This is asymptotically
82+
faster than the naive \u0398(n^3) algorithm for sufficiently large n.
83+
84+
Space complexity:
85+
Uses additional memory for temporary submatrices and padding; overall
86+
space complexity is O(n^2).
87+
88+
Notes:
89+
This function expects square matrices whose size is a power of two.
90+
Matrices of other sizes are handled by `strassen` which pads to the
91+
next power of two.
7892
"""
7993
if matrix_dimensions(matrix_a) == (2, 2):
8094
return default_matrix_multiplication(matrix_a, matrix_b)
@@ -106,6 +120,15 @@ def actual_strassen(matrix_a: list, matrix_b: list) -> list:
106120

107121
def strassen(matrix1: list, matrix2: list) -> list:
108122
"""
123+
Multiply two matrices using Strassen's divide-and-conquer algorithm.
124+
125+
Time complexity:
126+
\u0398(n^{log_2 7}) \u2248 \u0398(n^{2.8074}) (recurrence T(n) = 7 T(n/2) + \u0398(n^2)).
127+
128+
Space complexity:
129+
O(n^2) due to padding and temporary matrices used during recursion.
130+
131+
Examples:
109132
>>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]])
110133
[[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]]
111134
>>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]])

0 commit comments

Comments
 (0)