Sponsored
Sponsored
This approach involves iterating over each column in the grid formed by the strings. For each column, we compare the characters from top to bottom to ensure that they are in non-decreasing order. If a column is found to be unsorted, it needs to be deleted. We maintain a count of such unsorted columns and return this count at the end.
Time Complexity: O(m * n), where m is the number of strings and n is the length of each string. We iterate over each column and each row within the column.
Space Complexity: O(1), no additional space is used except for a few variables.
1function minDeletionSize(strs) {
2 let delCount = 0;
3 const columnCount = strs[0].length;
4
5 for (let col = 0; col < columnCount; col++) {
6 for (let row = 1; row < strs.length; row++) {
7 if (strs[row][col] < strs[row - 1][col]) {
8 delCount++;
9 break;
10 }
11 }
12 }
13
14 return delCount;
15}
16
17// Example Usage
18let strs = ["cba", "daf", "ghi"];
19console.log(minDeletionSize(strs));
JavaScript iterates over each column and compares elements from top to bottom to detect if the column is unsorted. If an unsorted column is found, the deletion count is incremented.
In this approach, instead of checking each column individually with a nested loop, we try to reduce the checks by using internal helper functions or flags. This might reduce the overhead for checking conditions multiple times, though generally both approaches might occupy similar time complexity due to the input constraints.
Time Complexity: O(m * n)
Space Complexity: O(1)
1
This C implementation checks each column with the help of a boolean flag to optimize the escape from the nested loop once an unsorted column is detected, reducing unnecessary further checks for that column.