Tutorialspoint
Problem
Solution
Submissions

If a Matrix is Symmetric

Certification: Basic Level Accuracy: 40% Submissions: 5 Points: 5

Write a C# program to determine if a given square matrix is symmetric. A matrix is symmetric if it equals its own transpose (i.e., A = A^T). This means that for each element A[i,j] in the matrix, A[i,j] = A[j,i].

Example 1
  • Input: matrix = [
    [1, 2, 3],
    [2, 5, 6],
    [3, 6, 9]
    ]
  • Output: true
  • Explanation:
    • Step 1: Check if the matrix is square (number of rows equals number of columns).
    • Step 2: For each element at position (i,j) where i is not equal to j, verify if the element at position (j,i) is equal.
    • Step 3: The transpose of the matrix is: [
      [1, 2, 3],
      [2, 5, 6],
      [3, 6, 9]
      ]
    • Step 4: When the original matrix equals its transpose, the matrix is symmetric.
Example 2
  • Input: matrix = [
    [1, 2],
    [3, 4]
    ]
  • Output: false
  • Explanation:
    • Step 1: Check if the matrix is square (number of rows equals number of columns).
    • Step 2: For each element at position (i,j) where i is not equal to j, verify if the element at position (j,i) is equal.
    • Step 3: The transpose of the matrix is: [
      [1, 3],
      [2, 4]
      ]
    • Step 4: When the original matrix does not equal its transpose, the matrix is not symmetric.
Constraints
  • 1 ≤ matrix.length ≤ 100
  • matrix[i].length == matrix.length (the matrix is square)
  • -1000 ≤ matrix[i][j] ≤ 1000
  • Time Complexity: O(n²)
  • Space Complexity: O(1)
ArraysNumberAirbnbSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Check if the matrix is square (n×n).
  • For each element at position (i,j), verify if element at position (j,i) is equal.
  • If any pair of elements doesn't match, the matrix is not symmetric.
  • Take advantage of symmetry to reduce comparisons (only need to check one half of the matrix).
  • Implement an efficient algorithm that minimizes redundant checks.

Steps to solve by this approach:

 Step 1: Verify the matrix is square by checking if the number of rows equals the number of columns.
 Step 2: Iterate through the matrix, but only check elements where i > j to avoid redundant comparisons.
 Step 3: For each position (i,j) where i > j, compare matrix[i,j] with matrix[j,i].
 Step 4: If any pair doesn't match, return false immediately.
 Step 5: If all pairs match, return true as the matrix is symmetric.

Submitted Code :