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.
1public class Solution {
2 public int minDeletionSize(String[] strs) {
3 int delCount = 0;
4 int columnCount = strs[0].length();
5
6 for (int col = 0; col < columnCount; col++) {
7 for (int row = 1; row < strs.length; row++) {
8 if (strs[row].charAt(col) < strs[row - 1].charAt(col)) {
9 delCount++;
10 break;
11 }
12 }
13 }
14
15 return delCount;
16 }
17
18 public static void main(String[] args) {
19 Solution sol = new Solution();
20 String[] strs = {"cba", "daf", "ghi"};
21 System.out.println(sol.minDeletionSize(strs));
22 }
23}
In Java, we handle the input as an array of strings. The nested loops iterate over the columns, and if any column is found unsorted, it's counted towards the deletion count.
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.