Matrices · Easy
A square matrix report needs only the primary diagonal from the top-left corner to the bottom-right corner. Other cells can contain unrelated large values. This is a diagonal selection exercise, not a request to total the entire matrix or both diagonals.
Return the signed sum of matrix[i][i] for every row index and exclude all off-diagonal cells.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ matrix: integer[][] }
Fields
- matrix is non-empty and square: every row has matrix.length integer entries.
- Row and column indexes are zero-based. The primary diagonal uses equal row and column indexes.
Output
Return value
- Return one integer sum. A 1×1 matrix returns its only value.
- Count only the primary diagonal, including its center once for an odd-sized matrix. Use a 64-bit integer in Java/C++.
Constraints
- 1 <= matrix.length <= 256; -1000000000 <= matrix[i][j] <= 1000000000.
- Do not mutate input. The input adapter reads all n² values; only the solution’s selection pass is O(n).
Examples
Example 1
{
"matrix": [
[
1,
20
],
[
30,
4
]
]
}Returns
5Example 2
{
"matrix": [
[
-9
]
]
}Returns
-9Required complexity
O(n) solution time and O(1) auxiliary solution space; reading the supplied matrix is O(n²)