# Determinant of a Matrix

Tue Feb 08 2022 08:29:37 GMT+0000 (UTC)

```class Solution
{
//Function to get cofactor of matrix[p][q] in temp[][].
static void getCofactor(int matrix[][], int temp[][], int p, int q, int n)
{
int i = 0, j = 0;

for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
//copying only those elements into temporary matrix
//which are not in given row and column.
if(row != p && col != q)
{
temp[i][j++] = matrix[row][col];

//if row is filled, we increase row index and
//reset column index.
if(j == n - 1)
{
j = 0;
i++;
}
}
}
}
}

//Function for finding determinant of matrix.
static int determinantOfMatrix(int matrix[][], int n)
{
int D = 0;

//base case
if (n == 1)
return matrix[0][0];

//creating a list to store Cofactors.
int temp[][]  = new int[n][n];

int sign = 1;

//iterating for each element of first row.
for (int i = 0; i < n; i++)
{
//getting Cofactor of matrix[0][i].
getCofactor(matrix, temp, 0, i, n);
D += sign * matrix[0][i] * determinantOfMatrix(temp, n - 1);

//terms are to be added with alternate sign so changing the sign.
sign = -sign;
}
//returning the determinant.
return D;
}
}```
content_copyCOPY

Determinant of a Matrix Given a square matrix of size N x N. The task is to find the determinant of this matrix. Example 1: Input: N = 4 matrix[][] = {{1, 0, 2, -1}, {3, 0, 0, 5}, {2, 1, 4, -3}, {1, 0, 5, 0}} Output: 30 Explanation: Determinant of the given matrix is 30. Example 2: Input: N = 3 matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 10, 9}} Output: 12 Explanation: Determinant of the given matrix is 12. Your Task: You don't need to read input or print anything. Complete the function determinantOfMatrix() that takes matrix and its size n as input parameters and returns the determinant of the matrix. Expected Time Complexity: O(N^4) Expected Auxiliary Space: O(N^2) Constraints: 1 <= N <= 8 -10 <= mat[i][j] <= 10

https://practice.geeksforgeeks.org/problems/determinant-of-a-matrix-1587115620/1/?track=DSASP-Matrix&batchId=190