LeetCode 2388: Change Null Values in a Table to the Previous Value
Problem Description
Explanation:
Given a table with null values, the task is to change those null values to the value from the previous non-null cell in the same column.
Algorithm:
- Iterate through each row of the table.
- For each cell, if it is null, update it with the value of the previous non-null cell in the same column.
- Keep track of the previous non-null value for each column.
Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the table. Space Complexity: O(n) where n is the number of columns in the table.
:
Solutions
class Solution {
public void fillTable(int[][] table) {
if (table == null || table.length == 0) {
return;
}
int numRows = table.length;
int numCols = table[0].length;
int[] prevValues = new int[numCols];
Arrays.fill(prevValues, -1);
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (table[i][j] == -1) {
table[i][j] = prevValues[j];
} else {
prevValues[j] = table[i][j];
}
}
}
}
}
Loading editor...