Delete Columns to Make Sorted II

medium greedy array string

Problem

You are given an array of n equal-length strings. Picture them as a grid: deleting a column removes the same character index from every string. Return the minimum number of columns to delete so that the remaining strings are in lexicographic (non-decreasing) order from top to bottom.

Inputstrs = ["ca", "bb", "ac"]
Output1
Delete column 0 ("c","b","a"), leaving ["a","b","c"] which is sorted top-to-bottom. Column 1 alone is not enough, so the answer is 1.

def min_deletion_size(strs):
    n = len(strs)
    sorted_pairs = [False] * (n - 1)
    deletions = 0
    for col in range(len(strs[0])):
        if any(not sorted_pairs[r] and strs[r][col] > strs[r + 1][col]
               for r in range(n - 1)):
            deletions += 1
            continue
        for r in range(n - 1):
            if strs[r][col] < strs[r + 1][col]:
                sorted_pairs[r] = True
    return deletions
function minDeletionSize(strs) {
  const n = strs.length;
  const sortedPairs = new Array(n - 1).fill(false);
  let deletions = 0;
  for (let col = 0; col < strs[0].length; col++) {
    let bad = false;
    for (let r = 0; r < n - 1; r++)
      if (!sortedPairs[r] && strs[r][col] > strs[r + 1][col]) bad = true;
    if (bad) { deletions++; continue; }
    for (let r = 0; r < n - 1; r++)
      if (strs[r][col] < strs[r + 1][col]) sortedPairs[r] = true;
  }
  return deletions;
}
class Solution {
    public int minDeletionSize(String[] strs) {
        int n = strs.length;
        boolean[] sortedPairs = new boolean[n - 1];
        int deletions = 0;
        for (int col = 0; col < strs[0].length(); col++) {
            boolean bad = false;
            for (int r = 0; r < n - 1; r++)
                if (!sortedPairs[r] && strs[r].charAt(col) > strs[r + 1].charAt(col)) bad = true;
            if (bad) { deletions++; continue; }
            for (int r = 0; r < n - 1; r++)
                if (strs[r].charAt(col) < strs[r + 1].charAt(col)) sortedPairs[r] = true;
        }
        return deletions;
    }
}
int minDeletionSize(vector<string>& strs) {
    int n = strs.size();
    vector<bool> sortedPairs(n - 1, false);
    int deletions = 0;
    for (int col = 0; col < (int)strs[0].size(); col++) {
        bool bad = false;
        for (int r = 0; r < n - 1; r++)
            if (!sortedPairs[r] && strs[r][col] > strs[r + 1][col]) bad = true;
        if (bad) { deletions++; continue; }
        for (int r = 0; r < n - 1; r++)
            if (strs[r][col] < strs[r + 1][col]) sortedPairs[r] = true;
    }
    return deletions;
}
Time: O(n · k) Space: O(n)