Sum Both Diagonals of a Square Matrix
Given a nonempty square integer matrix, return the sum of its primary and secondary diagonal entries. Count a shared center entry only once. Ignore entries…
Given a nonempty square integer `matrix`, return the sum of its primary and secondary diagonal entries. Count a shared center entry only once. Ignore entries that are on neither diagonal.
1 <= matrix.length <= 500. Every row has matrix.length entries. All entries are integers from -1000 through 1000. The visualizer uses square matrices with at most 8 rows; larger valid inputs are execution-only. Here n is the number of rows and columns. Complexity excludes copying performed by the platform wrapper.
Example 1: input matrix = [[7]]; output 7. The one entry belongs to both diagonals and is counted once.
Example 2: input matrix = [[1,2],[3,4]]; output 10. Every entry belongs to a diagonal in this 2 by 2 matrix.
Example 3: input matrix = [[1,2,3],[4,5,6],[7,8,9]]; output 25. Count 1, 3, 5, 7 and 9; the center 5 contributes once.
Category: Arrays. Topic: arrays. Difficulty: Easy. Patterns: math.