Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Print matrix in zig-zag fashion
Next article icon

Program to find Determinant of a Matrix

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

The determinant of a Matrix is defined as a special number that is defined only for square matrices (matrices that have the same number of rows and columns). A determinant is used in many places in calculus and other matrices related to algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of a linear equation and finding the inverse of a matrix.

Determinant of 2 x 2 Matrix:

1
determinant of 2 x 2 matrix

Determinant of 3 x 3 Matrix:

2
determinant of 3 x 3 matrix

How to calculate?

The value of the determinant of a matrix can be calculated by the following procedure: 

  • For each element of the first row or first column get the cofactor of those elements.
  • Then multiply the element with the determinant of the corresponding cofactor. 
  • Finally, add them with alternate signs. As a base case, the value of the determinant of a 1*1 matrix is the single value itself. 

The cofactor of an element is a matrix that we can get by removing the row and column of that element from that matrix.

C++
#include <bits/stdc++.h> using namespace std;  // Function for finding the determinant of a matrix. int getDet(vector<vector<int>>& mat, int n) {        // Base case: if the matrix is 1x1     if (n == 1) {         return mat[0][0];     }          // Base case for 2x2 matrix     if (n == 2) {         return mat[0][0] * mat[1][1] -                 mat[0][1] * mat[1][0];     }          // Recursive case for larger matrices     int res = 0;     for (int col = 0; col < n; ++col) {                // Create a submatrix by removing the first          // row and the current column         vector<vector<int>> sub(n - 1, vector<int>(n - 1));         for (int i = 1; i < n; ++i) {             int subcol = 0;             for (int j = 0; j < n; ++j) {                                // Skip the current column                 if (j == col) continue;                                 // Fill the submatrix                 sub[i - 1][subcol++] = mat[i][j];              }         }                // Cofactor expansion         int sign = (col % 2 == 0) ? 1 : -1;          res += sign * mat[0][col] * getDet(sub, n - 1);     }          return res;  }  // Driver program to test the above function int main() {     vector<vector<int>> mat = { { 1, 0, 2, -1 },                                  { 3, 0, 0, 5 },                                  { 2, 1, 4, -3 },                                  { 1, 0, 5, 0 } };     cout << getDet(mat, mat.size()) << endl;     return 0; } 
C
#include <stdio.h> #include <stdlib.h>  #define N 4   // Function for finding the determinant of a matrix. int getDet(int mat[N][N], int n) {        // Base case: if the matrix is 1x1     if (n == 1) {         return mat[0][0];     }          // Base case for 2x2 matrix     if (n == 2) {         return mat[0][0] * mat[1][1] -                 mat[0][1] * mat[1][0];     }          // Recursive case for larger matrices     int res = 0;     for (int col = 0; col < n; ++col) {                // Create a submatrix by removing the          // first row and the current column         int sub[N][N]; // Submatrix         for (int i = 1; i < n; ++i) {             int subcol = 0;             for (int j = 0; j < n; ++j) {                                // Skip the current column                 if (j == col) continue;                                 // Fill the submatrix                 sub[i - 1][subcol++] = mat[i][j];              }         }                // Cofactor expansion         int sign = (col % 2 == 0) ? 1 : -1;          res += sign * mat[0][col] * getDet(sub, n - 1);     }          return res;  }  // Driver program to test the above function int main() {     int mat[N][N] = { { 1, 0, 2, -1 },                       { 3, 0, 0, 5 },                       { 2, 1, 4, -3 },                       { 1, 0, 5, 0 } };     printf("%d\n", getDet(mat, N));     return 0; } 
Java
// Function for finding the determinant of a matrix. public class GfG {     public static int getDet(int[][] mat, int n) {                // Base case: if the matrix is 1x1         if (n == 1) {             return mat[0][0];         }                  // Base case for 2x2 matrix         if (n == 2) {             return mat[0][0] * mat[1][1] -                     mat[0][1] * mat[1][0];         }                  // Recursive case for larger matrices         int res = 0;         for (int col = 0; col < n; ++col) {                        // Create a submatrix by removing the first              // row and the current column             int[][] sub = new int[n - 1][n - 1];             for (int i = 1; i < n; ++i) {                 int subcol = 0;                 for (int j = 0; j < n; ++j) {                                        // Skip the current column                     if (j == col) continue;                                           // Fill the submatrix                     sub[i - 1][subcol++] = mat[i][j];                  }             }                          // Cofactor expansion             int sign = (col % 2 == 0) ? 1 : -1;              res += sign * mat[0][col] * getDet(sub, n - 1);         }                  return res;      }      // Driver program to test the above function     public static void main(String[] args) {         int[][] mat = { { 1, 0, 2, -1 },                          { 3, 0, 0, 5 },                          { 2, 1, 4, -3 },                          { 1, 0, 5, 0 } };         System.out.println(getDet(mat, mat.length));     } } 
Python
# Function for finding the determinant of a matrix. def getDet(mat, n):        # Base case: if the matrix is 1x1     if n == 1:         return mat[0][0]          # Base case for 2x2 matrix     if n == 2:         return mat[0][0] * mat[1][1] - \                mat[0][1] * mat[1][0]          # Recursive case for larger matrices     res = 0     for col in range(n):                # Create a submatrix by removing the first          # row and the current column         sub = [[0] * (n - 1) for _ in range(n - 1)]         for i in range(1, n):             subcol = 0             for j in range(n):                                # Skip the current column                 if j == col:                     continue                                  # Fill the submatrix                 sub[i - 1][subcol] = mat[i][j]                 subcol += 1                  # Cofactor expansion         sign = 1 if col % 2 == 0 else -1         res += sign * mat[0][col] * getDet(sub, n - 1)          return res  # Driver program to test the above function mat = [[1, 0, 2, -1],        [3, 0, 0, 5],        [2, 1, 4, -3],        [1, 0, 5, 0]] print(getDet(mat, len(mat))) 
C#
// Function for finding the determinant of a matrix. using System; using System.Linq;  class Determinant {     public static int GetDet(int[,] mat, int n) {                // Base case: if the matrix is 1x1         if (n == 1) {             return mat[0, 0];         }                  // Base case for 2x2 matrix         if (n == 2) {             return mat[0, 0] * mat[1, 1] -                     mat[0, 1] * mat[1, 0];         }                  // Recursive case for larger matrices         int res = 0;         for (int col = 0; col < n; col++) {                        // Create a submatrix by removing the first              // row and the current column             int[,] sub = new int[n - 1, n - 1];             for (int i = 1; i < n; i++) {                 int subcol = 0;                 for (int j = 0; j < n; j++) {                                        // Skip the current column                     if (j == col) continue;                                          // Fill the submatrix                     sub[i - 1, subcol++] = mat[i, j];                 }             }                          // Cofactor expansion             int sign = (col % 2 == 0) ? 1 : -1;             res += sign * mat[0, col] * GetDet(sub, n - 1);         }                  return res;     }      // Driver program to test the above function     static void Main() {         int[,] mat = { { 1, 0, 2, -1 },                         { 3, 0, 0, 5 },                         { 2, 1, 4, -3 },                         { 1, 0, 5, 0 } };         Console.WriteLine(GetDet(mat, mat.GetLength(0)));     } } 
JavaScript
// Function for finding the determinant of a matrix. function getDet(mat, n) {      // Base case: if the matrix is 1x1     if (n === 1) {         return mat[0][0];     }          // Base case for 2x2 matrix     if (n === 2) {         return mat[0][0] * mat[1][1] -                 mat[0][1] * mat[1][0];     }          // Recursive case for larger matrices     let res = 0;     for (let col = 0; col < n; col++) {              // Create a submatrix by removing the first          // row and the current column         let sub = Array.from({ length: n - 1 }, () => new Array(n - 1));         for (let i = 1; i < n; i++) {             let subcol = 0;             for (let j = 0; j < n; j++) {                              // Skip the current column                 if (j === col) continue;                                  // Fill the submatrix                 sub[i - 1][subcol++] = mat[i][j];             }         }                  // Cofactor expansion         let sign = (col % 2 === 0) ? 1 : -1;         res += sign * mat[0][col] * getDet(sub, n - 1);     }          return res; }  // Driver program to test the above function let mat = [ [ 1, 0, 2, -1 ],             [ 3, 0, 0, 5 ],             [ 2, 1, 4, -3 ],             [ 1, 0, 5, 0 ] ]; console.log(getDet(mat, mat.length)); 

Output
30 

Time Complexity: O(n3)
Space Complexity: O(n2), Auxiliary space used for storing cofactors.

Note: In the above recursive approach when the size of the matrix is large it consumes more stack size.

Determinant of a Matrix using Determinant properties

We calculates the determinant of an N x N matrix using Gaussian elimination and a series of transformations that reduce the matrix to upper triangular form.

  • Converting the given matrix into an upper triangular matrix using determinant properties 
  • The determinant of the upper triangular matrix is the product of all diagonal elements. 
  • Iterating every diagonal element and making all the elements down the diagonal as zero using determinant properties 
  • If the diagonal element is zero then search for the next non-zero element in the same column.

There exist two cases:

  • Case 1: If there is no non-zero element. In this case, the determinant of a matrix is zero 
  • Case 2: If there exists a non-zero element there exist two cases 
    • Case A: If the index is with a respective diagonal row element. Using the determinant properties make all the column elements down to it zero
    • Case B: Swap the row with respect to the diagonal element column and continue the Case A operation.
C++
#include <iostream> #include <vector> #include <cmath> // For pow function using namespace std;  // Function to get determinant of a matrix int getDet(vector<vector<int>>& mat) {        int n = mat.size();        int num1, num2, det = 1, index, total = 1;         // Temporary array for storing row     vector<int> temp(n + 1);       // Loop for traversing the diagonal elements     for (int i = 0; i < n; i++) {         index = i;           // Finding the index which has non-zero value         while (index < n && mat[index][i] == 0) {             index++;         }                if (index == n) // If there is no non-zero element         {             continue; // The determinant of the matrix is zero         }         if (index != i) {                        // Loop for swapping the diagonal element row and index row             for (int j = 0; j < n; j++) {                 swap(mat[index][j], mat[i][j]);             }                        // Determinant sign changes when we shift rows             det *= pow(-1, index - i);         }          // Storing the values of diagonal row elements         for (int j = 0; j < n; j++) {             temp[j] = mat[i][j];         }                // Traversing every row below the diagonal element         for (int j = i + 1; j < n; j++) {             num1 = temp[i]; // Value of diagonal element             num2 = mat[j][i]; // Value of next row element              // Traversing every column of row and             // multiplying to every row             for (int k = 0; k < n; k++) {                                // Making the diagonal element and next row element equal                 mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);             }             total *= num1;          }     }      // Multiplying the diagonal elements to get determinant     for (int i = 0; i < n; i++) {         det *= mat[i][i];     }        return (det / total); // Det(kA)/k = Det(A); }  // Driver code int main() {     vector<vector<int>> mat = {         { 1, 0, 2, -1 },         { 3, 0, 0, 5 },         { 2, 1, 4, -3 },         { 1, 0, 5, 0 }     };     cout << getDet(mat) << endl;     return 0; } 
Java
import java.util.Arrays;  public class GfG {      // Function to get the determinant of a matrix     static int getDet(int[][] mat) {         int n = mat.length;          int num1, num2, det = 1, index, total = 1;                 // Temporary array for storing row         int[] temp = new int[n + 1];          // Loop for traversing the diagonal elements         for (int i = 0; i < n; i++) {             index = i;              // Finding the index which has a non-zero value             while (index < n && mat[index][i] == 0) {                 index++;             }             if (index == n) { // If there is no non-zero element                 continue; // The determinant of the matrix is zero             }             if (index != i) {                                // Loop for swapping the diagonal element                 // row and index row                 for (int j = 0; j < n; j++) {                     int tempSwap = mat[index][j];                     mat[index][j] = mat[i][j];                     mat[i][j] = tempSwap;                 }                 // Determinant sign changes when we shift rows                 det *= Math.pow(-1, index - i);             }              // Storing the values of diagonal row elements             for (int j = 0; j < n; j++) {                 temp[j] = mat[i][j];             }             // Traversing every row below the diagonal element             for (int j = i + 1; j < n; j++) {                 num1 = temp[i]; // Value of diagonal element                 num2 = mat[j][i]; // Value of next row element                  // Traversing every column of row and multiplying                 // to every row                 for (int k = 0; k < n; k++) {                                        // Making the diagonal element and next row                      // element equal                     mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);                 }                 total *= num1;              }         }          // Multiplying the diagonal elements to get determinant         for (int i = 0; i < n; i++) {             det *= mat[i][i];         }          return (det / total); // Det(kA)/k = Det(A);     }      // Driver code     public static void main(String[] args) {         int[][] mat = {             { 1, 0, 2, -1 },             { 3, 0, 0, 5 },             { 2, 1, 4, -3 },             { 1, 0, 5, 0 }         };         System.out.println(getDet(mat));     } } 
Python
# Python program to find Determinant of a matrix def getDet(mat):      n  = len(mat)     temp = [0]*n  # temporary array for storing row     total = 1     det = 1  # initialize result      # loop for traversing the diagonal elements     for i in range(0, n):         index = i  # initialize the index          # finding the index which has non zero value         while(index < n and mat[index][i] == 0):             index += 1          if(index == n):  # if there is non zero element             # the determinant of matrix as zero             continue          if(index != i):                        # loop for swapping the diagonal element              # row and index row             for j in range(0, n):                 mat[index][j], mat[i][j] = mat[i][j], mat[index][j]              # determinant sign changes when we shift rows             # go through determinant properties             det = det*int(pow(-1, index-i))          # storing the values of diagonal row elements         for j in range(0, n):             temp[j] = mat[i][j]          # traversing every row below the diagonal element         for j in range(i+1, n):             num1 = temp[i]     # value of diagonal element             num2 = mat[j][i]   # value of next row element              # traversing every column of row             # and multiplying to every row             for k in range(0, n):                                # multiplying to make the diagonal                 # element and next row element equal                 mat[j][k] = (num1*mat[j][k]) - (num2*temp[k])              total = total * num1  # Det(kA)=kDet(A);      # multiplying the diagonal elements to get determinant     for i in range(0, n):         det = det*mat[i][i]      return int(det/total)  # Det(kA)/k=Det(A);   # Drivers code if __name__ == "__main__":     # mat=[[6 1 1][4 -2 5][2 8 7]]      mat = [[1, 0, 2, -1], [3, 0, 0, 5], [2, 1, 4, -3], [1, 0, 5, 0]]         print(getDet(mat)) 
C#
using System;  class MatrixDeterminant {     // Function to get the determinant of a matrix     static int getDet(int[,] mat)     {         int n = mat.GetLength(0);          int num1, num2, det = 1, index, total = 1;                // Temporary array for storing row         int[] temp = new int[n + 1];          // Loop for traversing the diagonal elements         for (int i = 0; i < n; i++)         {             index = i;              // Finding the index which has a non-zero value             while (index < n && mat[index, i] == 0)             {                 index++;             }                         // If there is no non-zero element             if (index == n)             {                 // The determinant of the matrix is zero                 continue;              }             if (index != i)             {                 // Loop for swapping the diagonal element                 // row and index row                 for (int j = 0; j < n; j++)                 {                     int tempSwap = mat[index, j];                     mat[index, j] = mat[i, j];                     mat[i, j] = tempSwap;                 }                                // Determinant sign changes when we shift rows                 det *= (int)Math.Pow(-1, index - i);             }              // Storing the values of diagonal row elements             for (int j = 0; j < n; j++)             {                 temp[j] = mat[i, j];             }                        // Traversing every row below the diagonal element             for (int j = i + 1; j < n; j++)             {                 num1 = temp[i]; // Value of diagonal element                 num2 = mat[j, i]; // Value of next row element                  // Traversing every column of row and multiplying                  // to every row                 for (int k = 0; k < n; k++)                 {                     // Making the diagonal element and next row                     // element equal                     mat[j, k] = (num1 * mat[j, k]) - (num2 * temp[k]);                 }                 total *= num1;             }         }          // Multiplying the diagonal elements to get determinant         for (int i = 0; i < n; i++)         {             det *= mat[i, i];         }          return (det / total); // Det(kA)/k = Det(A);     }      // Driver code     static void Main()     {         int[,] mat = {             { 1, 0, 2, -1 },             { 3, 0, 0, 5 },             { 2, 1, 4, -3 },             { 1, 0, 5, 0 }         };         Console.WriteLine(getDet(mat));     } } 
JavaScript
// Function to get the determinant of a matrix function determinantOfMatrix(mat) {     const n = mat.length;     let det = 1;     let total = 1;      // Temporary array for storing row     const temp = new Array(n + 1).fill(0);      // Loop for traversing the diagonal elements     for (let i = 0; i < n; i++) {         let index = i;          // Finding the index which has a non-zero value         while (index < n && mat[index][i] === 0) {             index++;         }         if (index === n) {             continue; // The determinant of the matrix is zero         }         if (index !== i) {                      // Swapping the diagonal element row and index row             for (let j = 0; j < n; j++) {                 [mat[index][j], mat[i][j]] = [mat[i][j], mat[index][j]];             }                          // Determinant sign changes when we shift rows             det *= Math.pow(-1, index - i);         }          // Storing the values of diagonal row elements         for (let j = 0; j < n; j++) {             temp[j] = mat[i][j];         }          // Traversing every row below the diagonal element         for (let j = i + 1; j < n; j++) {             const num1 = temp[i]; // Value of diagonal element             const num2 = mat[j][i]; // Value of next row element              // Traversing every column of row and multiplying              // to every row             for (let k = 0; k < n; k++) {                              // Making the diagonal element and next row                  // element equal                 mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);             }             total *= num1;          }     }      // Multiplying the diagonal elements to get determinant     for (let i = 0; i < n; i++) {         det *= mat[i][i];     }      return (det / total); // Det(kA)/k = Det(A); }  // Driver code const mat = [     [1, 0, 2, -1],     [3, 0, 0, 5],     [2, 1, 4, -3],     [1, 0, 5, 0] ]; console.log(determinantOfMatrix(mat)); 

Output
30 

Time complexity: O(n3) 
Auxiliary Space: O(n), Space used for storing row.

Determinant of a Matrix using NumPy package in Python

There is a built-in function or method in linalg module of NumPy package in python. It can be called numpy.linalg.det(mat) which returns the determinant value of the matrix mat passed in the argument.



Next Article
Print matrix in zig-zag fashion

K

kartik
Improve
Article Tags :
  • Mathematical
  • Matrix
  • DSA
Practice Tags :
  • Mathematical
  • Matrix

Similar Reads

    Matrix Data Structure
    Matrix Data Structure is a two-dimensional array arranged in rows and columns. It is commonly used to represent mathematical matrices and is fundamental in various fields like mathematics, computer graphics, and data processing. Matrices allow for efficient storage and manipulation of data in a stru
    2 min read
    Matrix or Grid or 2D Array - Complete Tutorial
    Matrix or Grid is a two-dimensional array mostly used in mathematical and scientific calculations. It is also considered as an array of arrays, where array at each index has the same size. Representation of Matrix Data Structure:As you can see from the below image, the elements are organized in rows
    11 min read
    Row-wise vs column-wise traversal of matrix
    Two common ways of traversing a matrix are row-major-order and column-major-order Row Major Order: When matrix is accessed row by row. Column Major Order: When matrix is accessed column by column.Examples: Input : mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output : Row-wise: 1 2 3 4 5 6 7 8 9 Col-wi
    6 min read
    Applications of Matrices and Determinants
    Applications of Matrices and Determinants: One application of matrices and determinants is that they can be used to solve linear equations in two or three variables. Matrices and determinants are also used to check the consistency of any system, whether they are consistent or not. This is the most u
    6 min read

    Basic Operations on Matrix

    Traverse a given Matrix using Recursion
    Given a matrix mat[][] of size n x m, the task is to traverse this matrix using recursion.Examples: Input: mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Output: 1 2 3 4 5 6 7 8 9Input: mat[][] = [[11, 12, 13], [14, 15, 16], [17, 18, 19]]Output: 11 12 13 14 15 16 17 18 19Approach: Check If the current p
    5 min read
    Rotate Matrix Clockwise by 1
    Given a square matrix, the task is to rotate its elements clockwise by one step.Examples:Input 1 2 34 5 6 7 8 9Output: 4 1 27 5 3 8 9 6Input: 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12The idea is to use nested loops to move elements in four directions (right
    9 min read
    Sort the given matrix
    Given a m x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that the matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= m-1, the first element is greater than or equal to the last
    5 min read
    Search element in a sorted matrix
    Given a sorted matrix mat[][] of size nxm and an element x, the task is to find if x is present in the matrix or not. Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row i, where 1 <= i <= n-1, the first element of row i is greater than or equal
    13 min read
    Program to find transpose of a matrix
    Given a matrix of size n X m, find the transpose of the matrix. Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of mat[n][m] is obtained by changing mat[i][j] to mat[j][i].Example:Approach using (N^2) spaceRun a nested loop using two integ
    9 min read
    Adjoint and Inverse of a Matrix
    Given a square matrix, find the adjoint and inverse of the matrix. We strongly recommend you to refer determinant of matrix as a prerequisite for this. Adjoint (or Adjugate) of a matrix is the matrix obtained by taking the transpose of the cofactor matrix of a given square matrix is called its Adjoi
    15+ min read
    Program to find Determinant of a Matrix
    The determinant of a Matrix is defined as a special number that is defined only for square matrices (matrices that have the same number of rows and columns). A determinant is used in many places in calculus and other matrices related to algebra, it actually represents the matrix in terms of a real n
    15+ min read

    Easy problems on Matrix

    Print matrix in zig-zag fashion
    Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: {{1, 2, 3}{4, 5, 6}{7, 8, 9}}Output: 1 2 4 7 5 3 6 8 9Input : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]Output:: 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16Thi
    10 min read
    Program for scalar multiplication of a matrix
    Given a 2D matrix mat[][] with n rows and m columns and a scalar element k, the task is to find out the scalar product of the given matrix.Examples: Input: mat[][] = [[2, 3], [5, 4]]k = 5Output: [[10, 15], [25, 20]]Input:mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]k = 4Output: [[4, 8, 12], [16, 20, 2
    4 min read
    Print a given matrix in spiral form
    Given a matrix mat[][] of size m x n, the task is to print all elements of the matrix in spiral form.Examples: Input: mat[][] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]Output: [ 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 ]Example of matrix in spiral formInput: mat[]
    14 min read
    Find distinct elements common to all rows of a matrix
    Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order. Examples: Input : mat[][] = { {2, 1, 4, 3}, {1, 2, 3, 2}, {3, 6, 2, 3}, {5, 2, 5, 3} } Output : 2 3 Input : mat[][] = { {12, 1, 14, 3, 16}, {14, 2, 1, 3,
    15+ min read
    Find unique elements in a matrix
    Given a matrix mat[][] having n rows and m columns. The task is to find unique elements in the matrix i.e., those elements which are not repeated in the matrix or those elements whose frequency is 1. Examples: Input: mat[][] = [[2, 1, 4, 3], [1, 2, 3, 2], [3, 6, 2, 3], [5, 2, 5, 3]]Output: 4 6Input:
    5 min read
    Find maximum element of each row in a matrix
    Given a matrix mat[][], the task is to find the maximum element of each row.Examples: Input: mat[][] = [[1, 2, 3] [1, 4, 9] [76, 34, 21]]Output :3976Input: mat[][] = [[1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]]Output :216556The idea is to run the loop for no_of_rows. Check each element inside the r
    4 min read
    Shift matrix elements row-wise by k
    Given a square matrix mat[][] and a number k. The task is to shift the first k elements of each row to the right of the matrix. Examples : Input : mat[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} k = 2 Output :mat[N][N] = {{3, 1, 2} {6, 4, 5} {9, 7, 8}} Input : mat[N][N] = {{1, 2, 3, 4} {5, 6, 7, 8} {9
    6 min read
    Swap major and minor diagonals of a square matrix
    Given a square matrix mat[][] of order n*n, the task is to swap the elements of major and minor diagonals.The major and minor diagonal matrix explanation is given below:Major Diagonal Elements of a Matrix: The Major Diagonal Elements are the ones that occur from the Top Left of the Matrix Down To th
    6 min read
    Squares of Matrix Diagonal Elements
    Given an integer matrix mat[][] of odd dimensions, the task is to find the square of the elements of the Primary and Secondary diagonals.The Primary and Secondary diagonal matrix explanation is given below:Primary Diagonal Elements of a Matrix: The Primary Diagonal Elements are the ones that occur f
    11 min read
    Sum of middle row and column in Matrix
    Given an integer matrix of odd dimensions (3 * 3, 5 * 5). then the task is to find the sum of the middle row & column elements. Examples: Input : 2 5 7 3 7 2 5 6 9 Output : Sum of middle row = 12 Sum of middle column = 18 Input : 1 3 5 6 7 3 5 3 2 1 1 2 3 4 5 7 9 2 1 6 9 1 5 3 2 Output : Sum of
    7 min read
    Program to check idempotent matrix
    Given a square matrix mat[][] of order n*n, the task is to check if it is an Idempotent Matrix or not.Idempotent matrix: A matrix is said to be an idempotent matrix if the matrix multiplied by itself returns the same matrix, i.e. the matrix mat[][] is said to be an idempotent matrix if and only if M
    5 min read
    Program to check diagonal matrix and scalar matrix
    Given a square matrix mat[][] of order n*n, the task is to check if it is a Diagonal Matrix and Scalar matrix.Diagonal Matrix: A square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main di
    9 min read
    Program to check Identity Matrix
    Given a square matrix mat[][] of order n*n, the task is to check if it is an Identity Matrix.Identity Matrix: A square matrix is said to be an identity matrix if the elements of main diagonal are one and all other elements are zero. The identity Matrix is also known as the Unit Matrix. Examples: Inp
    5 min read
    Mirror of matrix across diagonal
    Given a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in a way: swap the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. Print the 2-D array obtained in a mat
    14 min read
    Program for addition of two matrices
    Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. Approach: Below is the idea to solve the problem.Iterate over every cell of matrix (i, j), add the corresponding values of the two matrices
    5 min read
    Program for subtraction of matrices
    Given two m x n matrices m1 and m2, the task is to subtract m2 from m1 and return res.Input: m1 = {{1, 2}, {3, 4}}, m2 = {{4, 3}, {2, 1}}Output: {{-3, -1}, {1, 3}}Input: m1 = {{3, 3, 3}, {3, 3, 3}}, m1 = {{2, 2, 2}, {1, 1, 1}},Output: {{1, 1, 1}, {2, 2, 2}},We traverse both matrices element by eleme
    5 min read

    Intermediate problems on Matrix

    Program for Conway's Game Of Life | Set 1
    Given a Binary Matrix mat[][] of order m*n. A cell with a value of zero is a Dead Cell, while a cell with a value of one is a Live Cell. The state of cells in a matrix mat[][] is known as Generation. The task is to find the next generation of cells based on the following rules:Any live cell with few
    12 min read
    Program to multiply two matrices
    Given two matrices, the task is to multiply them. Matrices can either be square or rectangular:Examples: (Square Matrix Multiplication)Input: m1[m][n] = { {1, 1}, {2, 2} }m2[n][p] = { {1, 1}, {2, 2} }Output: res[m][p] = { {3, 3}, {6, 6} }(Rectangular Matrix Multiplication)Input: m1[3][2] = { {1, 1},
    7 min read
    Rotate an Image 90 Degree Counterclockwise
    Given an image represented by m x n matrix, rotate the image by 90 degrees in counterclockwise direction. Please note the dimensions of the result matrix are going to n x m for an m x n input matrix.Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13Input: 1
    6 min read
    Check if all rows of a matrix are circular rotations of each other
    Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1 Output: Yes All rows are rotated permutation of each other. Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2 Output: No Explanation : As 3, 2, 1
    8 min read
    Largest Cross Bordered Square
    Given a matrix mat[][] of size n x n where every element is either 'O' or 'X', the task is to find the size of the largest square subgrid that is completely surrounded by 'X', i.e. the largest square where all its border cells are 'X'. Examples: Input: mat[][] = [ ['X', 'X'], ['X', 'X'] ]Output: 2Ex
    15 min read
    Count zeros in a row wise and column wise sorted matrix
    Given a n x n binary matrix (elements in matrix can be either 1 or 0) where each row and column of the matrix is sorted in ascending order, count number of 0s present in it.Examples: Input: [0, 0, 0, 0, 1][0, 0, 0, 1, 1][0, 1, 1, 1, 1][1, 1, 1, 1, 1][1, 1, 1, 1, 1]Output: 8Input: [0, 0][0, 0]Output:
    6 min read
    Queries in a Matrix
    Given two integers m and n, that describes the order m*n of a matrix mat[][], initially filled with integers from 1 to m*n sequentially in a row-major order. Also, there is a 2d array query[][] consisting of q queries, which contains three integers each, where the first integer t describes the type
    15 min read
    Find pairs with given sum such that elements of pair are in different rows
    Given a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row.Examples: Input : mat[][] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 1
    15+ min read
    Find all permuted rows of a given row in a matrix
    Given a matrix mat[][] of order m*n, and an index ind. The task is to find all the rows in the matrix mat[][] which are permutations of rows at index ind.Note: All the elements of a row are distinct.Examples: Input: mat[][] = [[3, 1, 4, 2], [1, 6, 9, 3], [1, 2, 3, 4], [4, 3, 2, 1]] ind = 3 Output: 0
    9 min read
    Find number of transformation to make two Matrix Equal
    Given two matrices a and b of size n*m. The task is to find the required number of transformation steps so that both matrices become equal. Print -1 if this is not possible. The transformation step is as follows: Select any one matrix out of two matrices. Choose either row/column of the selected mat
    8 min read
    Inplace (Fixed space) M x N size matrix transpose
    Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it's diagonal (try yourself). How to transpose an arbitrary size matr
    15+ min read
    Minimum flip required to make Binary Matrix symmetric
    Given a Binary Matrix mat[][] of size n x n, consisting of 1s and 0s. The task is to find the minimum flips required to make the matrix symmetric along the main diagonal.Examples : Input: mat[][] = [[0, 0, 1], [1, 1, 1], [1, 0, 0]];Output: 2Value of mat[1][0] is not equal to mat[0][1].Value of mat[2
    8 min read
    Magic Square of Odd Order
    Given a positive integer n, your task is to generate a magic square of order n * n. A magic square of order n is an n * n grid filled with the numbers 1 through n² so that every row, every column, and both main diagonals each add up to the same total, called the magic constant (or magic sum) M. Beca
    15+ min read

    Hard problems on Matrix

    Number of Islands
    Given an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
    15+ min read
    A Boolean Matrix Question
    Given a boolean matrix mat where each cell contains either 0 or 1, the task is to modify it such that if a matrix cell matrix[i][j] is 1 then all the cells in its ith row and jth column will become 1.Examples:Input: [[1, 0], [0, 0]]Output: [[1, 1], [1, 0]]Input: [[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0
    15+ min read
    Matrix Chain Multiplication
    Given the dimension of a sequence of matrices in an array arr[], where the dimension of the ith matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. When two matrices of size m*
    15+ min read
    Maximum size rectangle binary sub-matrix with all 1s
    Given a 2d binary matrix mat[][], the task is to find the maximum size rectangle binary-sub-matrix with all 1's. Examples: Input: mat = [ [0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 0, 0] ]Output : 8Explanation : The largest rectangle with only 1's is from (1, 0) to (2, 3) which is[1, 1, 1, 1][
    15 min read
    Construct Ancestor Matrix from a Given Binary Tree
    Given a Binary Tree where all values are from 0 to n-1. Construct an ancestor matrix mat[n][n] where the ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of jmat[i][j] = 0, otherwiseExamples: Input: Output: {{0 1 1} {0 0 0} {0 0 0}}Input: Output: {{0 0 0 0 0 0} {1 0 0 0 1 0} {0 0
    15+ min read
    K'th element in spiral form of matrix
    Given a matrix of size n * m. You have to find the kth element which will obtain while traversing the matrix spirally starting from the top-left corner of the matrix.Examples:Input: mat[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], k = 4Output: 6Explanation: Spiral traversal of matrix: {1, 2, 3, 6, 9,
    13 min read
    Largest Plus or '+' formed by all ones in a binary square matrix
    Given an n × n binary matrix mat consisting of 0s and 1s. Your task is to find the size of the largest ‘+’ shape that can be formed using only 1s. A ‘+’ shape consists of a center cell with four arms extending in all four directions (up, down, left, and right) while remaining within the matrix bound
    10 min read
    Shortest path in a Binary Maze
    Given an M x N matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, and
    15+ min read
    Maximum sum square sub-matrix of given size
    Given a 2d array mat[][] of order n * n, and an integer k. Your task is to find a submatrix of order k * k, such that sum of all the elements in the submatrix is maximum possible.Note: Matrix mat[][] contains zero, positive and negative integers.Examples:Input: k = 3mat[][] = [ [ 1, 2, -1, 4 ] [ -8,
    15+ min read
    Validity of a given Tic-Tac-Toe board configuration
    A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach this board position after some moves or not.Note that every arbitrary filled grid of 9 spaces isn't valid e.g. a grid filled with 3 X and 6 O isn't valid situation because ea
    15+ min read
    Minimum Initial Points to Reach Destination
    Given a m*n grid with each cell consisting of positive, negative, or no points i.e., zero points. From a cell (i, j) we can move to (i+1, j) or (i, j+1) and we can move to a cell only if we have positive points ( > 0 ) when we move to that cell. Whenever we pass through a cell, points in that cel
    15+ min read
    Program for Sudoku Generator
    Given an integer k, the task is to generate a 9 x 9 Sudoku grid having k empty cells while following the below set of rules:In all 9 submatrices 3x3, the elements should be 1-9, without repetition.In all rows, there should be elements between 1-9, without repetition.In all columns, there should be e
    15+ 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