Leetcode Problem 1572. Matrix Diagonal Sum

1572. Matrix Diagonal Sum

Leetcode Solutions

Iterating over Diagonal Elements

  1. Initialize n to the length of the matrix (number of rows/columns).
  2. Initialize ans to 0 to store the sum of the diagonal elements.
  3. Loop from i = 0 to i = n - 1:
    • Add mat[i][i] to ans (primary diagonal).
    • Add mat[i][n - 1 - i] to ans (secondary diagonal).
  4. If n is odd, subtract the central element mat[n / 2][n / 2] from ans.
  5. Return ans.
UML Thumbnail

Using Two Pointers for Diagonal Traversal

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...