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 of strings that all have the same length, write them one per row to form a grid of letters. A column is sorted when its letters, read from top to bottom, are in alphabetical order. Return the number of columns that are not sorted, which is the number of columns you must delete so that every remaining column is sorted.

Example 1
Input: strs = ["cba", "daf", "ghi"]
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
Input: strs = ["a", "b"]
Output: 0
Example 3
Input: strs = ["zyx", "wvu", "tsr"]
Output: 3
Solution

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.

The strings cba, daf and ghi written as rows 0 to 2 of a grid. Column 0 reads c, d, g and column 2 reads a, f, i; both never drop and are kept. Column 1 reads b, a, h: a is smaller than b above it, so column 1 is deleted.

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) gives the letter in row row and column col. Comparing two of these with < compares their character codes, and the letters a to z have codes in alphabetical order, so 'a' < 'b' is true.

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 works in these steps:

  1. First, set a counter deleted to 0. It will hold the number of unsorted columns.
  2. Visit the columns with a loop over col, from 0 up to strs[0].length(). Every string has the same length, so the first string's length is the number of columns.
  3. Inside, a second loop moves row down the column, starting at 1, and compares the letter in row with the letter in row - 1, the row above it.
  4. When the lower letter is smaller, add 1 to deleted and leave the inner loop with break, so the outer loop moves on to the next column.
  5. When every column has been checked, return deleted.

The main method runs the three examples, two equal rows, a single row, and a grid whose only step back is in its last row.

Java
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:

Output
[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], gives 1, for column 1. In [zyx, wvu, tsr] every letter is smaller than the one above it, so all 3 columns go. [aa, aa] gives 0 because equal letters are not a step back.

With the single row [abc], the inner loop starts at row 1, which does not exist, so it never runs and nothing is deleted. The last line, [abc, bcd, cda], gives 1: column 2 reads c, d, a, and only the last comparison, a below d, finds the step back.

The break matters for the count. Without it, the method adds 1 for every step back instead of every unsorted column. For [zyx, wvu, tsr], each column has two steps back, and that version returns 6 instead of 3.

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 break can only cut a column short.
  • Space: O(1), because the method reads the letters in place with charAt and keeps only the counter and the two loop positions.

Reading a grid one column at a time also comes up in Valid Sudoku, which checks every row, every column and every 3 by 3 box of a 9 by 9 board for repeated digits.