MATDIAGSUM - Editorial

Prerequisites: Matrix, Loops, Observation.

Problem: Given a N x N square matrix, find the sum of both primary as well as secondary diagonal elements.

Solution Approach:

We iterate through the rows of the matrix, and for each row, we access the corresponding elements on both diagonals. For the primary diagonal, the row index is equal to the column index, and for the secondary diagonal, the row index is equal to (N - column index - 1), where N is the size of the matrix. We accumulate the values of these elements into a sum variable. If the row index is equal to the column index, we only add the value of the element once to avoid counting it twice for both diagonals. Finally, we return the total sum computed.

Time Complexity: O(N) as we just need to iterate through first column.
Space Complexity: O(1).