Tutorialspoint
Problem
Solution
Submissions

Check if a Matrix is Symmetric

Certification: Basic Level Accuracy: 33.33% Submissions: 9 Points: 10

Write a C++ program to check if a given square matrix is symmetric. A matrix is symmetric if it is equal to its transpose.

Example 1
  • Input: matrix = [ [1, 2, 3], [2, 4, 5], [3, 5, 6] ]
  • Output: true
  • Explanation:
    • Step 1: Calculate the transpose of the matrix by swapping elements across the diagonal.
    • Step 2: Check if element at position (i,j) equals element at position (j,i) for all valid i,j.
    • Step 3: Verify that matrix[0][1] = matrix[1][0] = 2, matrix[0][2] = matrix[2][0] = 3, and matrix[1][2] = matrix[2][1] = 5.
    • Step 4: Since all elements match their counterparts across the diagonal, return true.
Example 2
  • Input: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
  • Output: false
  • Explanation:
    • Step 1: Calculate the transpose of the matrix by swapping elements across the diagonal.
    • Step 2: Check if element at position (i,j) equals element at position (j,i) for all valid i,j.
    • Step 3: Verify that matrix[0][1] = 2 ≠ matrix[1][0] = 4, which means the matrix is not symmetric.
    • Step 4: Return false as we found elements that don't match across the diagonal.
Constraints
  • The matrix must be a square matrix
  • The matrix can have a maximum size of 100x100
  • Time Complexity: O(n²), where n is the size of the matrix
  • Space Complexity: O(1) (no extra space needed for in-place checking)
ArraysDeloitteApple
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

  • Compare the matrix with its transpose.
  • Use nested loops to check if each element at position (i, j) is equal to the element at position (j, i).

Steps to solve by this approach:

 Step 1: Define a function is_symmetric that takes a constant 2D vector as parameter.
 Step 2: Get the size of the matrix (number of rows/columns).
 Step 3: Use nested loops to compare each element with its transpose position.
 Step 4: If any element doesn't match its transpose counterpart, return false.
 Step 5: If all elements match their transpose counterparts, return true.
 Step 6: In main, create a matrix, call the function, and print the result.

Submitted Code :