Skip to content

955. Delete Columns to Make Sorted II 👍

  • Time: $O(n \cdot |\texttt{A}|)$, where $n = |\texttt{A[0]}|$
  • Space: $O(|\texttt{A}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int minDeletionSize(vector<string>& A) {
    const int n = A[0].length();
    int ans = 0;
    // sorted[i] := true if A[i] < A[i + 1]
    vector<bool> sorted(A.size() - 1);

    for (int j = 0; j < n; ++j) {
      int i;
      for (i = 0; i + 1 < A.size(); ++i)
        if (!sorted[i] && A[i][j] > A[i + 1][j]) {
          ++ans;
          break;
        }
      // already compared each pair, update the sorted array if needed
      if (i + 1 == A.size())
        for (i = 0; i + 1 < A.size(); ++i)
          sorted[i] = sorted[i] || A[i][j] < A[i + 1][j];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int minDeletionSize(String[] A) {
    final int n = A[0].length();
    int ans = 0;
    // sorted[i] := true if A[i] < A[i + 1]
    boolean[] sorted = new boolean[A.length - 1];

    for (int j = 0; j < n; ++j) {
      int i;
      for (i = 0; i + 1 < A.length; ++i)
        if (!sorted[i] && A[i].charAt(j) > A[i + 1].charAt(j)) {
          ++ans;
          break;
        }
      // already compared each pair, update the sorted array if needed
      if (i + 1 == A.length)
        for (i = 0; i + 1 < A.length; ++i)
          sorted[i] = sorted[i] || A[i].charAt(j) < A[i + 1].charAt(j);
    }

    return ans;
  }
}