← back

Determinant of a 4x4 Matrix using Laplace's Expansion

#13 · Linear Algebra · Hard

⊣ Solve on deep-ml.com

Problem

Calculate the determinant of a 4x4 matrix using Laplace's expansion (cofactor expansion).

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def determinant_4x4(matrix: list[list[int|float]]) -> float:
    def det(m):
        n = len(m)
        if n == 1:
            return m[0][0]
        if n == 2:
            return m[0][0] * m[1][1] - m[0][1] * m[1][0]
        result = 0
        for col in range(n):
            # Build minor by removing row 0 and column col
            minor = []
            for row in range(1, n):
                minor.append([m[row][c] for c in range(n) if c != col])
            sign = (-1) ** col
            result += sign * m[0][col] * det(minor)
        return result
    return float(det(matrix))

Explanation

  1. Use recursive cofactor expansion along the first row.
  2. For each element in the first row, build the minor matrix by removing that element's row and column.
  3. The cofactor is (-1)^(row+col) det(minor). Sum element cofactor across the first row.
  4. Base cases: 1x1 returns the element; 2x2 uses ad - bc directly.

Complexity

  • Time: O(n!) in general, but O(1) for fixed 4x4
  • Space: O(n) recursion depth, with minor matrices at each level