Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Prim's Algorithm in Python
Next article icon

Strassen algorithm in Python

Last Updated : 01 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Strassen's algorithm is an efficient method for matrix multiplication. It reduces the number of arithmetic operations required for multiplying two matrices by decomposing them into smaller submatrices and performing recursive multiplication. Strassen's algorithm is based on the divide-and-conquer approach and is particularly useful for large matrices.

Strassen Algorithm:

  • If the size of the matrices is small enough (e.g., 1x1 or 2x2), perform the standard matrix multiplication.
  • Divide each input matrix into four equally sized submatrices.
  • Calculate seven products of these submatrices using addition and subtraction operations.
  • Use these products to compute the four quadrants of the resulting matrix using addition and subtraction operations.

How Strassen algorithm works?

Consider two matrices:

A = [[1, 3], [7, 5]]
B = [[6, 8], [4, 2]]

We want to compute the product C=A×B.

  1. Initialization:
    • Start with the two input matrices A and B.
  2. Base Case Check:
    • Since both matrices A and B are 2x2, which is small enough, we perform standard matrix multiplication.
  3. Partition Matrices:
    • Partition matrices A and B into four submatrices each:
      • A11=[1​], A12=[3​], A21=[7​], A22=[5​]
      • B11=[6​], B12=[8​], B21=[4​], B22=[2​]
  4. Recursive Multiplication:
    • Recursively calculate seven products:
      • P1=A11×(B12−B22)=1×(8−2)=6
      • P2=(A11+A12)×B22=(1+3)×2=8
      • P3=(A21+A22)×B11=(7+5)×6=72
      • P4=A22×(B21−B11)=5×(4−6)=−10
      • P5=(A11+A22)×(B11+B22)=(1+5)×(6+2)=36
      • P6=(A12−A22)×(B21+B22)=(3−5)×(4+2)=−12
      • P7=(A11−A21)×(B11+B12)=(1−7)×(6+8)=−96
  5. Combine Results:
    • Calculate the four quadrants of the resulting matrix C:
      • C11=P5+P4−P2+P6=36+(−10)−8+(−12)=6
      • C12=P1+P2=6+8=14
      • C21=P3+P4=72+(−10)=62
      • C22=P5+P1−P3−P7=36+6−72−(−96)=66

Example Output:

The resulting matrix C (Result of A×B) is:

C = [[6, 14],
[62, 66]]

Python Implementation for Strassen algorithm:

Python
import numpy as np  def strassen(A, B):     n = len(A)          if n <= 2:  # Base case         return np.dot(A, B)          # Partition matrices into submatrices     mid = n // 2     A11 = A[:mid, :mid]     A12 = A[:mid, mid:]     A21 = A[mid:, :mid]     A22 = A[mid:, mid:]     B11 = B[:mid, :mid]     B12 = B[:mid, mid:]     B21 = B[mid:, :mid]     B22 = B[mid:, mid:]          # Recursive multiplication     P1 = strassen(A11, B12 - B22)     P2 = strassen(A11 + A12, B22)     P3 = strassen(A21 + A22, B11)     P4 = strassen(A22, B21 - B11)     P5 = strassen(A11 + A22, B11 + B22)     P6 = strassen(A12 - A22, B21 + B22)     P7 = strassen(A11 - A21, B11 + B12)          # Combine results to form C     C11 = P5 + P4 - P2 + P6     C12 = P1 + P2     C21 = P3 + P4     C22 = P5 + P1 - P3 - P7          # Combine quadrants to form C     C = np.vstack((np.hstack((C11, C12)), np.hstack((C21, C22))))     return C  # Example usage: A = np.array([[1, 3], [7, 5]]) B = np.array([[6, 8], [4, 2]]) C = strassen(A, B) print("Matrix C (Result of A * B):\n", C) 

Output
Matrix C (Result of A * B):  [[18 14]  [62 66]] 

Complexity Analysis:

  • Time Complexity: The time complexity of Strassen's algorithm is approximately O(n^2.81), where n is the size of the matrices. Although it reduces the number of multiplications, it increases the number of additions and subtractions.
  • Space Complexity: Strassen's algorithm has a space complexity of O(n^2) due to the recursive calls and the additional space required for submatrices.

Next Article
Prim's Algorithm in Python

S

srinam
Improve
Article Tags :
  • DSA
  • Python-DSA

Similar Reads

  • Tarjan's Algorithm in Python
    Tarjan's algorithm is used to find strongly connected components (SCCs) in a directed graph. It efficiently finds groups of vertices such that each vertex in a group has a path to every other vertex in the same group. Let's illustrate the working of Tarjan's algorithm with an example: Consider the f
    2 min read
  • Searching Algorithms in Python
    Searching algorithms are fundamental techniques used to find an element or a value within a collection of data. In this tutorial, we'll explore some of the most commonly used searching algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation Search, and Jump Search.
    6 min read
  • Kahn's Algorithm in Python
    Kahn's Algorithm is used for topological sorting of a directed acyclic graph (DAG). The algorithm works by repeatedly removing nodes with no incoming edges and recording them in a topological order. Here's a step-by-step implementation of Kahn's Algorithm in Python. Example: Input: V=6 , E = {{2, 3}
    4 min read
  • Dial's Algorithm in Python
    Dial's algorithm is a graph algorithm used for the finding the shortest path in a graph with the non-negative edge weights. It is an optimization of the Dijkstra's algorithm and is particularly efficient for the graphs with the bounded range of the edge weights. What is Dial's Algorithm?The Dial's a
    4 min read
  • Prim's Algorithm in Python
    Prim's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, undirected graph. The MST is a subset of the edges that connects all vertices in the graph with the minimum possible total edge weight. The algorithm starts with an empty spanning tree.The idea is to
    5 min read
  • Kruskal's Algorithm in Python
    Kruskal’s Algorithm is a greedy algorithm used to find MST in the graph. A minimum spanning tree (MST) is a spanning tree with a weight less than or equal to the weight of every other spanning tree. Kruskal’s Algorithm sorts all edges of the given graph in increasing order. Then it keeps on adding n
    4 min read
  • Kosaraju's Algorithm in Python
    What is Kosaraju's Algorithm?Kosaraju's Algorithm is a classic graph theory algorithm used to find the Strongly Connected Components (SCCs) in a directed graph. A strongly connected component is a maximal subgraph where every vertex is reachable from every other vertex. Kosaraju's algorithm is effic
    3 min read
  • Floyd-Warshall Algorithm in Python
    The Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen Warshall, is fundamental in computer science and graph theory. It is used to find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is highly efficient and can handle graphs with both posi
    3 min read
  • Boruvka's Algorithm using Python
    Boruvka's algorithm is a greedy algorithm for finding the Minimum Spanning Tree (MST) in a connected, weighted, and undirected graph. It was one of the first algorithms for this problem and is named after Otakar Borůvka, who introduced it in 1926. This algorithm works by repeatedly finding the short
    11 min read
  • Bitwise Algorithm in Python
    Bitwise algorithms refer to the use of bitwise operators to manipulate individual bits of data. Python provides a set of bitwise operators such as AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>). These operators are commonly used in tasks like encryption, com
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences