Delete Columns To Make Sorted Problem
Description
LeetCode Problem 944.
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:
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.
Example 1:
Input: strs = ["cba","daf","ghi"]
Output: 1
Explanation: The grid looks as follows:
cba
daf
ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
Example 2:
Input: strs = ["a","b"]
Output: 0
Explanation: The grid looks as follows:
a
b
Column 0 is the only column and is sorted, so you will not delete any columns.
Example 3:
Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: The grid looks as follows:
zyx
wvu
tsr
All 3 columns are not sorted, so you will delete all 3.
Constraints:
- n == strs.length
- 1 <= n <= 100
- 1 <= strs[i].length <= 1000
- strs[i] consists of lowercase English letters.
Solution
Approach: Check Each Column Top to Bottom
Each column is judged on its own: deleting one column does not change whether another column is sorted. So the answer is simply the number of columns that are not sorted.
For each column index col, walk down the rows and compare each character with the one above it:
- If some
strs[row][col] < strs[row - 1][col], the column is out of order. Count it and stop scanning this column, since one bad pair is enough. - If no such pair exists, the column is sorted and stays.
"Sorted" here means non-decreasing, so equal letters next to each other are fine: only a strictly smaller letter below a larger one breaks the order. Using <= instead of < would wrongly delete columns like ('c', 'e', 'e').
For strs = ["cba","daf","ghi"]: column 0 is c, d, g (sorted), column 1 is b, a, h (a < b, not sorted), column 2 is a, f, i (sorted). One column is deleted.
Complexity: O(n · m) time and O(1) space, where n is the number of strings and m is their length.
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
rows, cols = len(strs), len(strs[0])
deleted = 0
for col in range(cols):
for row in range(1, rows):
if strs[row][col] < strs[row - 1][col]:
deleted += 1 # this column is not sorted
break # one bad pair is enough
return deleted
Now write it from memory
Close the write-up and solve it yourself against the tests.