Delete Columns to Make Sorted III in C++


Suppose we have an array A of N strings. Each string is consists of lowercase letters, all are of same length. Now, we can choose any set of deletion indices, and for each string, we will delete all the characters in those indices.Now consider we have taken a set of deletion indices D such that after deletions, the final array has every element in lexicographic sequence.

For clarity, A[0] is in lexicographic order (So A[0][0] <= A[0][1] <= ... <= A[0][n - 1]), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= ... <= A[1][n - 1]), and so on. (Here n is the size of the strings). We have to find the minimum possible value of the size of D.

So, if the input is like ["cbcdb","ccbxc"], then the output will be 3

To solve this, we will follow these steps −

  • ret := 0

  • n := size of A

  • m := size of A[0]

  • Define an array lis of size (m + 1) and fill this with 1

  • for initialize i := 0, when i < m, update (increase i by 1), do −

    • for initialize j := 0, when j < i, update (increase j by 1), do −

      • ok := true

      • for initialize k := 0, when k < n, update (increase k by 1), do −

        • if A[k, j] > A[k, i], then

          • ok := false

          • Come out from the loop

      • if ok is non-zero, then −

        • lis[i] := maximum of lis[j] + 1 and lis[i]

        • ret := maximum of ret and lis[i]

  • if ret is same as 0, then −

    • return m - 1

  • return m - ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minDeletionSize(vector<string>& A){
      int ret = 0;
      int n = A.size();
      int m = A[0].size();
      vector<int> lis(m + 1, 1);
      for (int i = 0; i < m; i++) {
         for (int j = 0; j < i; j++) {
            bool ok = true;
            for (int k = 0; k < n; k++) {
               if (A[k][j] > A[k][i]) {
                  ok = false;
                  break;
               }
            }
            if (ok) {
               lis[i] = max(lis[j] + 1, lis[i]);
               ret = max(ret, lis[i]);
            }
         }
      }
      if (ret == 0)
      return m - 1;
      return m - ret;
   }
};
main(){
   Solution ob;
   vector<string> v = {"cbcdb","ccbxc"};
   cout << (ob.minDeletionSize(v));
}

Input

{"cbcdb","ccbxc"}

Output

3

Updated on: 04-Jun-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements