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).
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]]
To convert a square matrix to upper triangular, we zero out all elements where the row index is greater than the column index (i > j), as these lie below the main diagonal.
n of the square matrix.i from 0 to n-1.j from 0 to n-1.i > j, set matrix[i][j] = 0.#include <vector>
using namespace std;
class Solution {
public:
void convertToUpperTriangular(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
matrix[i][j] = 0;
}
}
}
}
};
class Solution {
public void convertToUpperTriangular(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
matrix[i][j] = 0;
}
}
}
}
}
def convertToUpperTriangular(matrix):
n = len(matrix)
for i in range(n):
for j in range(n):
if i > j:
matrix[i][j] = 0
function convertToUpperTriangular(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i > j) {
matrix[i][j] = 0;
}
}
}
}
Time Complexity: O(n²), where n is the matrix dimension. We traverse all n² elements once.
Space Complexity: O(1), as we modify the matrix in-place without extra space.
Your notes are automatically saved in your browser's local storage and will persist across sessions on this device.