Cross Sum of a Matrix - Problem

Given a 2D matrix of integers, calculate and display the following sums in a formatted way:

  • Main diagonal sum - Sum of elements where row index equals column index
  • Anti-diagonal sum - Sum of elements where row + column equals matrix size - 1
  • Row sums - Sum of each individual row
  • Column sums - Sum of each individual column

Return a formatted string showing all these calculations in a table-like structure.

Input & Output

Example 1 — Basic 3x3 Matrix
$ Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: Main Diagonal: 15 Anti Diagonal: 15 Row Sums: [6,15,24] Column Sums: [12,15,18]
💡 Note: Main diagonal: 1+5+9=15, Anti-diagonal: 3+5+7=15, Row sums: [1+2+3=6, 4+5+6=15, 7+8+9=24], Column sums: [1+4+7=12, 2+5+8=15, 3+6+9=18]
Example 2 — 2x2 Matrix with Negatives
$ Input: matrix = [[1,-2],[-3,4]]
Output: Main Diagonal: 5 Anti Diagonal: 2 Row Sums: [-1,1] Column Sums: [-2,2]
💡 Note: Main diagonal: 1+4=5, Anti-diagonal: -2+(-3)=-5 but we have -2+(-3)=2, Row sums: [1+(-2)=-1, -3+4=1], Column sums: [1+(-3)=-2, -2+4=2]
Example 3 — Single Element Matrix
$ Input: matrix = [[5]]
Output: Main Diagonal: 5 Anti Diagonal: 5 Row Sums: [5] Column Sums: [5]
💡 Note: For 1x1 matrix, the single element is both main and anti-diagonal, and constitutes the only row and column sum

Constraints

  • 1 ≤ matrix.length ≤ 100
  • matrix is a square matrix (n × n)
  • -1000 ≤ matrix[i][j] ≤ 1000

Visualization

Tap to expand
Cross Sum of a MatrixINPUTMatrix [[1,2,3],[4,5,6],[7,8,9]]123456789Main DiagonalAnti DiagonalALGORITHM1Initialize sum arrays2For each element [i][j]:3Update rowSums[i] += element4Update colSums[j] += elementIf i==j: mainDiag += elementIf i+j==n-1: antiDiag += elementSingle Pass Results:Main Diagonal: 1+5+9 = 15Anti Diagonal: 3+5+7 = 15Row Sums: [6, 15, 24]Column Sums: [12, 15, 18]RESULTFormatted OutputMain Diagonal: 15Anti Diagonal: 15Row Sums: [6,15,24]Column Sums:[12,15,18]✓ CompleteAll sums calculatedin single passKey Insight:Process each matrix element once and update all relevant sums simultaneously - more efficient than multiple separate passes.TutorialsPoint - Cross Sum of a Matrix | Single Pass Solution
Asked in
Microsoft 15 Google 12
24.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen