Click4Ai

39.

Medium

Write a function determinant_3x3(matrix) that computes the determinant of a 3×3 matrix using cofactor expansion along the first row.

**Formula:** For [[a,b,c],[d,e,f],[g,h,i]]:

det = a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g)

Example:

Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output: 0

**Explanation:** 1*(45-48) - 2*(36-42) + 3*(32-35) = -3 + 12 - 9 = 0

Constraints:

  • Input is always a 3×3 matrix
  • Return an integer or float
  • Test Cases

    Test Case 1
    Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    Expected: 0
    Test Case 2
    Input: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    Expected: 1
    Test Case 3
    Input: [[2, 1, 3], [0, 4, 5], [1, 0, 6]]
    Expected: 43
    + 2 hidden test cases