VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-check-matrix-upper-triangular/

⇱ Program to check if matrix is upper triangular - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to check if matrix is upper triangular

Last Updated : 7 May, 2025

Given a square matrix mat[][], the task is to determine whether it is in upper triangular form. A matrix is considered upper triangular if all elements below the main diagonal are zero, while the diagonal and elements above it can be any value.

👁 Image
Examples: 

Input: mat[][] = [[1, 2, 3]
[0, 5, 6]
[0, 0, 9]]
Output: Yes
Explanation: All elements below the main diagonal are 0, so the matrix is upper triangular.

Input: mat[][] = [[3, 2, 6, 7]
[0, 6, 6, 8]
[0, 0, 2, 4]
[0, 0, 0, 1]]
Output: Yes
Explanation: All elements below the main diagonal are 0, so the matrix is upper triangular.

Input: mat[][] = [[1, 2, 0]
[9, 8, 7]
[0, 4, 9]]
Output: No

Approach:

The idea is to loop through the lower half of the matrix (i.e., cells where row index i > column index j) and verify if each such cell contains zero. The observation that only elements below the diagonal affect whether a matrix is upper triangular. if any one of those elements is non-zero, we can immediately return false, indicating the matrix is not upper triangular.


Output
Yes

Time Complexity: O(n2), where n represents the number of rows and columns of the matrix.
Space Complexity: O(1), no extra space is required, so it is a constant.

Comment
Article Tags: