Check if Matrix is Square

67.6k
0

Given a matrix, check whether the matrix is a square matrix.

A square matrix has the same number of rows and columns. For example, a matrix with dimension 3 x 3 is square, while a matrix with dimension 2 x 3 is not square.

Example 1

Input: mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output: true

Explanation: The matrix has 3 rows and 3 columns, so the matrix is square.

Example 2

Input: mat = [[1, 2, 3], [4, 5, 6]]

Output: false

Explanation: The matrix has 2 rows and 3 columns, so the matrix is not square.

Approach

A matrix is square only if it has the same number of rows and columns. Since this property depends only on the matrix dimensions, there is no need to traverse its elements. Simply compare the row and column counts to determine the result.

Algorithm

  • Find the number of rows in the matrix, as the number of rows is one of the dimensions required to determine whether the matrix is square.

  • Check if the matrix is empty and return false, since an empty matrix does not have valid dimensions to compare.

  • Find the number of columns in the first row, as this gives the second dimension of the matrix.

  • Compare the number of rows and columns, since a matrix is square only when both dimensions are equal.

  • Return true if the two dimensions are equal; otherwise, return false.

Dry Run

if square

if square

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to check whether a matrix is square.
bool isSquareMatrix(vector<vector<int>>& mat) {
// Store total number of rows.
int n = mat.size();
// Handle an empty matrix.
if (n == 0) {
return false;
}
// Store total number of columns.
int m = mat[0].size();
// Compare row count and column count.
return n == m;
}
};
// Driver code.
int main() {
vector<vector<int>> mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Solution sol;
cout << (sol.isSquareMatrix(mat) ? "true" : "false") << "\n";
return 0;
}

Complexity Analysis

Time Complexity: O(1), only row count and column count are compared.

Space Complexity: O(1), only dimension variables are used.

Interview follow-up Questions

Equal row count and column count make a matrix square.

Arrays

Read Similar Blogs

Comments0