Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Diagonal product of a matrix - JavaScript
Suppose, we have a 2-D array representing a square matrix like this ?
const arr = [ [1, 3, 4, 2], [4, 5, 3, 5], [5, 2, 6, 4], [8, 2, 9, 3] ];
We are required to write a function that takes in this array and returns the product of the elements present at the principal diagonal of the matrix.
Principal Diagonal Elements
The principal diagonal consists of elements where the row index equals the column index (i === j). For this array, the elements present at the principal diagonal are:
1, 5, 6, 3
Hence the product should be: 1 × 5 × 6 × 3 = 90
Example
Following is the code to calculate the diagonal product:
const arr = [
[1, 3, 4, 2],
[4, 5, 3, 5],
[5, 2, 6, 4],
[8, 2, 9, 3]
];
const diagonalProduct = arr => {
let product = 1;
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr[i].length; j++){
if(i === j){
product *= arr[i][j];
}
}
}
return product;
};
console.log(diagonalProduct(arr));
90
Optimized Approach
We can optimize this by avoiding the nested loop since we only need diagonal elements:
const arr = [
[1, 3, 4, 2],
[4, 5, 3, 5],
[5, 2, 6, 4],
[8, 2, 9, 3]
];
const diagonalProductOptimized = arr => {
let product = 1;
for(let i = 0; i < arr.length; i++){
product *= arr[i][i];
}
return product;
};
console.log(diagonalProductOptimized(arr));
90
Comparison
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Nested Loop | O(n²) | O(1) |
| Single Loop | O(n) | O(1) |
Conclusion
The optimized single-loop approach is more efficient for calculating diagonal products, reducing time complexity from O(n²) to O(n). Use arr[i][i] to directly access diagonal elements.
