Upper Triangular Matrix Conversion

TCS NQT Coding Easy Go Ad-Free - ₹20/mo

Given a 2D square matrix of integers where all elements are non-zero, convert it into an upper triangular matrix by setting all elements below the main diagonal to zero. The main diagonal consists of elements where the row index equals the column index (i.e., for element at position (i, j), if i > j, set it to zero).

Examples:

Input: [[1, 2], [3, 4]]

Output: [[1, 2], [0, 4]]

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

Output: [[1, 2, 3], [0, 5, 6], [0, 0, 9]]

Input: [[5]]

Output: [[5]]

Constraints

  • The matrix is square (n x n) with 1 ≤ n ≤ 100.
  • All elements in the input matrix are non-zero integers.
  • After conversion, elements below the main diagonal are set to zero; elements on or above the diagonal remain unchanged.