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
JavaScript Program to Check if a Matrix is Symmetric
A symmetric matrix is a square matrix that equals its transpose, meaning element at position (i,j) equals element at position (j,i). In mathematical terms, A = AT, where A is the matrix and AT is its transpose.
In this article, we'll explore JavaScript programs to check if a given matrix is symmetric using different approaches.
Example Input and Output
Input: matrix = [[1, 2, 3], [2, 4, 5], [3, 5, 6]] Output: The matrix is symmetric: true Input: matrix = [[1, 2, 3], [2, 4, 5], [3, 9, 6]] Output: The matrix is symmetric: false
Using Transpose Matrix Comparison
This approach creates the transpose of the given matrix and compares it element by element with the original matrix.
function getTranspose(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
// Check if matrix is square
if (rows !== cols) {
return null;
}
const transpose = [];
for (let i = 0; i
Matrix: [ [ 1, 2, 3 ], [ 2, 4, 5 ], [ 3, 5, 6 ] ]
Is symmetric: true
Matrix: [ [ 1, 2, 3 ], [ 2, 4, 5 ], [ 3, 9, 6 ] ]
Is symmetric: false
Using Direct Element Comparison
This optimized approach directly compares matrix[i][j] with matrix[j][i] without creating a transpose matrix, using less memory.
function isSymmetricDirect(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
// Must be a square matrix
if (rows !== cols) {
return false;
}
// Compare only upper triangle with lower triangle
for (let i = 0; i {
console.log(`Test ${index + 1}:`, matrix);
console.log(`Is symmetric: ${isSymmetricDirect(matrix)}`);
console.log('---');
});
Test 1: [ [ 1, 2, 3 ], [ 2, 4, 5 ], [ 3, 5, 6 ] ]
Is symmetric: true
---
Test 2: [ [ 1, 2 ], [ 2, 1 ] ]
Is symmetric: true
---
Test 3: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Is symmetric: false
---
Test 4: [ [ 5 ] ]
Is symmetric: true
---
Complexity Comparison
| Approach | Time Complexity | Space Complexity | Advantages |
|---|---|---|---|
| Transpose Comparison | O(n²) | O(n²) | Easy to understand |
| Direct Comparison | O(n²) | O(1) | Memory efficient, faster |
Key Points
- A matrix must be square (rows = columns) to be symmetric
- Only need to check upper or lower triangle due to symmetry
- Direct comparison is more memory efficient than transpose approach
- Single-element matrices are always symmetric
Conclusion
The direct comparison method is more efficient as it uses constant space complexity and avoids creating a transpose matrix. Both approaches have the same time complexity but the direct method is the preferred solution for checking matrix symmetry in JavaScript.
