Leetcode 944. Delete Columns to Make Sorted
You are given an array of n
strings strs
, each of the same length.
The strings can be arranged such that there is one string per row, making a grid. For example, strs = ["abc", "bce", "cae"]
can be arranged as follows:
abc
bce
cae
You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 (‘a’, ‘b’, ‘c’) and 2 (‘c’, ‘e’, ‘e’) are sorted, while column 1 (‘b’, ‘c’, ‘a’) is not. So you would delete column 1.
Return the number of columns that you will delete.
class Solution {
public int minDeletionSize(String[] strs) {
int numCols = strs[0].length();
int numRows = strs.length;
int columnsToDelete = 0;
for (int col = 0; col < numCols; col++) {
for (int row = 1; row < numRows; row++) {
if (strs[row].charAt(col) < strs[row-1].charAt(col)) {
columnsToDelete++;
break;
}
}
}
return columnsToDelete;
}
}
This ensures that we can handle the worst-case scenario efficiently, whether sorting or checking constraints on the input strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?