Solving Leetcode Interviews in Seconds with AI: Matrix Diagonal Sum
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1572" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1: Input: mat = [[1,2,3], [4,5,6], [7,8,9]] Output: 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. Example 2: Input: mat = [[1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]] Output: 8 Example 3: Input: mat = [[5]] Output: 5 Constraints: n == mat.length == mat[i].length 1 <= n <= 100 1 <= mat[i][j] <= 100
Explanation
Here's an efficient solution to calculate the sum of matrix diagonals, considering the specified constraints:
- Approach: Iterate through the matrix, summing elements on the primary diagonal (where row index equals column index) and the secondary diagonal (where row index plus column index equals n-1). Avoid double-counting the center element when the matrix dimension is odd.
- Complexity:
- Runtime: O(n), where n is the number of rows/columns in the matrix.
- Storage: O(1).
Code
def diagonalSum(mat: list[list[int]]) -> int:
n = len(mat)
total_sum = 0
for i in range(n):
total_sum += mat[i][i] # Primary diagonal
total_sum += mat[i][n - 1 - i] # Secondary diagonal
if n % 2 == 1:
total_sum -= mat[n // 2][n // 2] # Subtract center element if n is odd
return total_sum