JavaScript Program to Efficiently Compute Sums of Diagonals of a Matrix

In a square matrix, there are two main diagonals: the primary diagonal (left-to-right) and the secondary diagonal (right-to-left). Computing their sums efficiently is a common programming task with practical applications in linear algebra and image processing.

In this article, we will explore two JavaScript approaches to calculate diagonal sums: a brute force method using nested loops and an optimized single-loop solution.

3x3 Matrix Diagonals 1 2 3 4 5 6 9 8 9 Primary: 1+5+9 = 15 Secondary: 3+5+9 = 17

Example

Input:
Matrix: [[1, 2, 3], [4, 5, 6], [9, 8, 9]]

Primary diagonal: 1 + 5 + 9 = 15
Secondary diagonal: 3 + 5 + 9 = 17

Output:
Primary Diagonal Sum: 15
Secondary Diagonal Sum: 17

Using Brute Force Approach

The brute force method uses nested loops to examine every element in the matrix, checking if each element belongs to either diagonal.

  • Primary diagonal: elements where row index equals column index (i === j)
  • Secondary diagonal: elements where i + j equals n-1 (or i === n-1-j)
let matrix = [[1, 2, 3], [4, 5, 6], [9, 8, 9]];
console.log("Matrix:", matrix);

function diagonalSumBruteForce(matrix) {
    let primarySum = 0;
    let secondarySum = 0;
    let n = matrix.length;
    
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            if (i === j) {
                primarySum += matrix[i][j];
            }
            if (i === n - 1 - j) {
                secondarySum += matrix[i][j];
            }
        }
    }
    
    console.log("Primary Diagonal Sum:", primarySum);
    console.log("Secondary Diagonal Sum:", secondarySum);
}

diagonalSumBruteForce(matrix);
Matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 9, 8, 9 ] ]
Primary Diagonal Sum: 15
Secondary Diagonal Sum: 17

Using Optimized Single Loop

The optimized approach directly accesses diagonal elements using a single loop, eliminating the need to check every matrix element.

let matrix = [[1, 2, 3], [4, 5, 6], [9, 8, 9]];
console.log("Matrix:", matrix);

function diagonalSumOptimized(matrix) {
    let primarySum = 0;
    let secondarySum = 0;
    let n = matrix.length;
    
    for (let i = 0; i < n; i++) {
        primarySum += matrix[i][i];              // Primary diagonal
        secondarySum += matrix[i][n - 1 - i];    // Secondary diagonal
    }
    
    console.log("Primary Diagonal Sum:", primarySum);
    console.log("Secondary Diagonal Sum:", secondarySum);
}

diagonalSumOptimized(matrix);
Primary Diagonal Sum: 15
Secondary Diagonal Sum: 17

Handling Edge Case: Odd-Sized Matrix

For matrices with odd dimensions, the center element is counted twice. Here's how to handle this:

function diagonalSumWithOverlapHandling(matrix) {
    let primarySum = 0;
    let secondarySum = 0;
    let n = matrix.length;
    
    for (let i = 0; i < n; i++) {
        primarySum += matrix[i][i];
        secondarySum += matrix[i][n - 1 - i];
    }
    
    // If matrix size is odd, subtract the center element once
    if (n % 2 === 1) {
        let center = Math.floor(n / 2);
        secondarySum -= matrix[center][center];
    }
    
    console.log("Primary Diagonal Sum:", primarySum);
    console.log("Secondary Diagonal Sum:", secondarySum);
    console.log("Total Sum:", primarySum + secondarySum);
}

let matrix3x3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
diagonalSumWithOverlapHandling(matrix3x3);
Primary Diagonal Sum: 15
Secondary Diagonal Sum: 15
Total Sum: 30

Complexity Comparison

Approach Time Complexity Space Complexity Efficiency
Brute Force O(n²) O(1) Less efficient
Optimized O(n) O(1) More efficient

Key Points

  • Primary diagonal elements have equal row and column indices (i === j)
  • Secondary diagonal elements satisfy i + j === n - 1
  • The optimized approach reduces time complexity from O(n²) to O(n)
  • Handle center element overlap in odd-sized matrices when summing both diagonals

Conclusion

The optimized single-loop approach is significantly more efficient for computing diagonal sums, reducing time complexity from O(n²) to O(n). This method directly accesses only the required diagonal elements, making it ideal for large matrices and performance-critical applications.

Updated on: 2026-03-15T23:19:01+05:30

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements