All practice tasks

Coding (Algo)

Total the Primary Matrix Diagonal

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

5

Example 2

{
  "matrix": [
    [
      -9
    ]
  ]
}

Returns

-9

Required complexity

O(n) solution time and O(1) auxiliary solution space; reading the supplied matrix is O(n²)

What this task practices

Total the Primary Matrix Diagonal is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as easy difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.