[LeetCode] Delete Columns to Make Sorted

944. Delete Columns to Make Sorted

You are given an array of n strings strs, all of the same length.

The strings can be arranged such that there is one on each line, making a grid. For example, strs = [“abc”, “bce”, “cae”] can be arranged as:

1
2
3
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minDeletionSize(vector<string>& strs) {
int n = strs.size(), m = strs[0].length();
int res = 0;
for(int i = 0; i < m; i++) {
bool fl = false;
for(int j = 0; j < n - 1; j++) {
if(strs[j][i] > strs[j+1][i]) fl = true;
}
res += fl;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/03/PS/LeetCode/delete-columns-to-make-sorted/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.