Delete Columns to Make Sorted
Write equal-length strings one under another and count the columns whose letters are not in alphabetical order.
Given an array strs
Example 1
Output: 1
Explanation: column 0 reads c, d, g (sorted), column 1 reads b, a, h (not sorted), column 2 reads a, f, i (sorted).
Example 2
Output: 0
Example 3
Output: 3
The Idea
Take three words, "cba", "daf" and "ghi", and write them on squared paper, one word per line, one letter per square. The letters line up into columns, like a small crossword. Reading across gives back the words; reading down a column gives a new list of letters, one from each word.
Look at the picture above. Each word is a row, numbered 0 to 2, and each position in the words is a column, numbered 0 to 2. Column 0 reads c, d, g: every letter comes later in the alphabet than the one above it, so the column is sorted. Column 2 reads a, f, i and is sorted too. Both are marked "never drops: keep".
Column 1 reads b, a, h. Going from row 0 to row 1, the letters step back from b to a, as the arrow shows. That one step back, marked "a is smaller than b above", is enough to spoil the column, so it has to go. The answer for Example 1 is 1.
The problem asks for the fewest deletions, which raises a question: could deleting one column ever fix another, or force a third to go? Look at the grid again. Removing column 1 leaves column 0 reading c, d, g and column 2 reading a, f, i, exactly as before. A column's letters come only from its own position in each word, so no deletion changes them.
So every column can be judged on its own. A sorted column never needs to be deleted, and an unsorted one always does. The answer is simply the number of unsorted columns.
Solution Approach
Turning that idea into code means settling three things: why counting the unsorted columns, instead of trying sets of columns to delete, gives the fewest deletions, how to check one column, and when to stop checking it.
Deciding each column on its own
What would a search for the fewest deletions look like without the idea above? It would try every set of columns to delete and check whether the rest are sorted. With m columns there are 2m such sets, so 20 columns already give over a million.
Deciding each column on its own skips all of that. Each column makes the choice that is best for it, keep if sorted and delete if not, and because columns do not affect each other, those choices together are the best answer for the whole grid. Settling each column with the choice that is best for that column alone, and never going back to it, is what makes this a greedy method.
Checking one column
How do we tell whether a column is sorted? Compare each letter with the letter just above it, in the same column. If no letter is smaller than the one above it, the column is sorted. Equal letters are fine: the column a, a still reads in alphabetical order.
In Java, strs[row].charAt(col)rowcol<'a' < 'b'
Stopping at the first step back
What happens once a column has a letter smaller than the one above it? The column is already known to be unsorted, and checking its remaining letters cannot change that. So the check counts the column once and moves straight on to the next column.
Java Solution
The method minDeletionSize
- First, set a counter
to 0. It will hold the number of unsorted columns.deleted - Visit the columns with a loop over
, from 0 up tocol . Every string has the same length, so the first string's length is the number of columns.strs[0].length() - Inside, a second loop moves
down the column, starting at 1, and compares the letter inrow with the letter inrow , the row above it.row - 1 - When the lower letter is smaller, add 1 to
and leave the inner loop withdeleted , so the outer loop moves on to the next column.break - When every column has been checked, return
.deleted
The main
import java.util.Arrays;
public class DeleteColumnsToMakeSorted {
public static int minDeletionSize(String[] strs) {
int deleted = 0;
for (int col = 0; col < strs[0].length(); col++) {
for (int row = 1; row < strs.length; row++) {
if (strs[row].charAt(col) < strs[row - 1].charAt(col)) {
deleted++; // a letter is smaller than the one above it
break; // this column is decided, go to the next
}
}
}
return deleted;
}
static void show(String... strs) {
System.out.println(Arrays.toString(strs) + " -> " + minDeletionSize(strs));
}
public static void main(String[] args) {
show("cba", "daf", "ghi");
show("a", "b");
show("zyx", "wvu", "tsr");
show("aa", "aa"); // equal letters count as sorted
show("abc"); // one row: nothing to compare
show("abc", "bcd", "cda"); // the only drop is in the last row
}
}
Running it prints:
[cba, daf, ghi] -> 1
[a, b] -> 0
[zyx, wvu, tsr] -> 3
[aa, aa] -> 0
[abc] -> 0
[abc, bcd, cda] -> 1
The grid from the picture, [cba, daf, ghi][zyx, wvu, tsr][aa, aa]
With the single row [abc][abc, bcd, cda]
The break[zyx, wvu, tsr]
Complexity
The work is one walk down each column, so it depends on n, the number of strings, and m, the length of each string.
- Time: O(n × m), because each of the m columns is read down its n letters at most once, and the
can only cut a column short.break - Space: O(1), because the method reads the letters in place with
and keeps only the counter and the two loop positions.charAt
Reading a grid one column at a time also comes up in