← back

Calculate 2x2 Matrix Inverse

#8 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the inverse of a 2x2 matrix. If the matrix is singular (determinant is zero), return None.

Solution

1
2
3
4
5
6
7
8
9
10
11
def inverse_2x2(matrix: list[list[float]]) -> list[list[float]]:
    a, b = matrix[0]
    c, d = matrix[1]
    det = a * d - b * c
    if det == 0:
        return None
    inv_det = 1 / det
    return [
        [d * inv_det, -b * inv_det],
        [-c * inv_det, a * inv_det]
    ]

Explanation

  1. For a 2x2 matrix [[a, b], [c, d]], the determinant is ad - bc.
  2. If the determinant is zero, the matrix is singular and has no inverse.
  3. The inverse is (1/det) * [[d, -b], [-c, a]] — swap the diagonal, negate the off-diagonal, and scale by 1/det.

Complexity

  • Time: O(1)
  • Space: O(1)