We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions is ["bc","az"].
Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.
For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1]), and so on.
Return the minimum possible value of D.length.
 

Example 1:
Input: ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is A = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]).
Note that A[0] > A[1] - the array A isn't necessarily in lexicographic order.


Example 2:
Input: ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row won't be lexicographically sorted.


Example 3:
Input: ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.

 



Note:

1 <= A.length <= 100
1 <= A[i].length <= 100

Difficulty: interview

Starter code:

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        

Solutions:
class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        dp = [(1, 1)] * len(A[0])
        for i in range(len(dp)):
            if i > 0:
                max_pre = None
                for pre in range(i - 1, -1, -1):
                    for word in A:
                        if word[pre] > word[i]:
                            pre -= 1
                            break
                    else:
                        if max_pre is None or dp[pre][1] > dp[max_pre][1]:
                            max_pre = pre

                max_len = 1 if max_pre is None else max(1, dp[max_pre][1] + 1)
                overall = max(dp[i - 1][0], max_len)
                dp[i] = (overall, max_len)
        # print(dp)
        return len(dp) - dp[-1][0]

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        dp = [(1, 1)] * len(A[0])
        for i in range(len(dp)):
            if i > 0:
                max_pre = None
                for pre in range(i - 1, -1, -1):
                    for word in A:
                        if word[pre] > word[i]:
                            pre -= 1
                            break
                    else:
                        if max_pre is None or dp[pre][1] > dp[max_pre][1]:
                            max_pre = pre

                max_len = 1 if max_pre is None else max(1, dp[max_pre][1] + 1)
                overall = max(dp[i - 1][0], max_len)
                dp[i] = (overall, max_len)
        return len(dp) - dp[-1][0]

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        H, W = len(A), len(A[0])
        
        def is_valid(j1: int, j2: int) -> bool:
            for i in range(H):
                if A[i][j1] > A[i][j2]:
                    return False
            return True
        f = [1 for _ in range(W)]
        max_v = 1
        for i in reversed(range(W - 1)):
            for j in range(i + 1, W):
                if is_valid(i, j):
                    f[i] = max(f[i], f[j] + 1)
            max_v = max(max_v, f[i])
        print(f)
        return W - max_v

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        W = len(A[0])
        dp = [1] * W
        for i in range(W-2, -1, -1):
            for j in range(i+1, W):
                if all(row[i] <= row[j] for row in A):
                    dp[i] = max(dp[i], 1 + dp[j])

        return W - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
      n = len(A[0])
      dp = [1 for _ in range(n)]
      for i in range(1, n):
        for j in range(i):
          if all(a[j] <= a[i] for a in A):
            dp[i] = max(dp[i], dp[j] + 1)
      
      return n - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        words = len(A[0])
        dp = [1] * words
        
        for i in range(words-2, -1, -1):
            for j in range(i+1, words):
                # for all rows that row[i] <= row[j] set dp[i] = max of dp[i], 1+dp[j]
                if all(row[i] <= row[j] for row in A):
                    dp[i] = max(dp[i], 1+dp[j])
        
        return words - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        n = len(A[0])
        dp = [1]*n
        for i in range(1, n):
            for j in range(i):
                if all(s[j] <= s[i] for s in A):
                    dp[i] = max(dp[i], dp[j] + 1)
        return n - max(dp)


#
# @lc app=leetcode id=960 lang=python3
#
# [960] Delete Columns to Make Sorted III
#
# https://leetcode.com/problems/delete-columns-to-make-sorted-iii/description/
#
# algorithms
# Hard (53.38%)
# Likes:    171
# Dislikes: 5
# Total Accepted:    4.5K
# Total Submissions: 8.5K
# Testcase Example:  '[\"babca\",\"bbazb\"]'
#
# We are given an array A of N lowercase letter strings, all of the same
# length.
# 
# Now, we may choose any set of deletion indices, and for each string, we
# delete all the characters in those indices.
# 
# For example, if we have an array A = [\"babca\",\"bbazb\"] and deletion indices
# {0, 1, 4}, then the final array after deletions is [\"bc\",\"az\"].
# 
# Suppose we chose a set of deletion indices D such that after deletions, the
# final array has every element (row) in lexicographic order.
# 
# For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= ... <=
# A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] <=
# A[1][1] <= ... <= A[1][A[1].length - 1]), and so on.
# 
# Return the minimum possible value of D.length.
# 
# 
# 
# 
# Example 1:
# 
# 
# Input: [\"babca\",\"bbazb\"]
# Output: 3
# Explanation: After deleting columns 0, 1, and 4, the final array is A =
# [\"bc\", \"az\"].
# Both these rows are individually in lexicographic order (ie. A[0][0] <=
# A[0][1] and A[1][0] <= A[1][1]).
# Note that A[0] > A[1] - the array A isn't necessarily in lexicographic
# order.
# 
# 
# 
# Example 2:
# 
# 
# Input: [\"edcba\"]
# Output: 4
# Explanation: If we delete less than 4 columns, the only row won't be
# lexicographically sorted.
# 
# 
# 
# Example 3:
# 
# 
# Input: [\"ghi\",\"def\",\"abc\"]
# Output: 0
# Explanation: All rows are already lexicographically sorted.
# 
# 
# 
# 
# 
# 
# 
# Note:
# 
# 
# 1 <= A.length <= 100
# 1 <= A[i].length <= 100
# 
#
class Solution:
    def minDeletionSize(self, A: List[str]) -> int:

        # Dynamic Programming
        # Let dp[k] be the number of columns that are kept in answering the question for input [row[k:] for row in A]. The above gives a simple recursion for dp[k].
        # Time  complexity: O(N x W^2) where N is the length of A, and W is the length of each word in A.
        # Space complexity: O(W)
        W = len(A[0])
        dp = [1] * W
        for i in range(W - 2, -1, -1):
            for j in range(i + 1, W):
                if all(row[i] <= row[j] for row in A):
                    dp[i] = max(dp[i], 1 + dp[j])

        return W - max(dp)

        



class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        n = len(A[0])
        dp = [1] * n
        for j in range(1, n):
            for i in range(j):
                if all(a[i] <= a[j] for a in A):
                    dp[j] = max(dp[j], dp[i] + 1)
        return n - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        m = len(A[0])
        n = len(A)
        dp = [1] * m
        for i in range(1, m):
            for j in range(i):
                if all(a[j] <= a[i] for a in A):
                    dp[i] = max(dp[i], dp[j] + 1)
        return m - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        ## https://leetcode.com/problems/delete-columns-to-make-sorted-iii/discuss/205679/C%2B%2BJavaPython-Maximum-Increasing-Subsequence
        
        m = len(A)
        n = len(A[0])
        dp = [1] * n
        res = n-1
        for j in range(1, n):
            for i in range(j):
                k = 0
                while k<m and A[k][i] <= A[k][j]:
                    k += 1
                if k == m and (1+dp[i])>dp[j]:
                    dp[j] = 1+dp[i]
                
                # if all(a[i] <= a[j] for a in A):
                #     dp[j] = max(dp[j], dp[i] + 1)
                
            res = min(res, n-dp[j])
        return res
                    


class Solution:
    def minDeletionSize(self, A):
        W = len(A[0])
        dp = [1] * W
        for j in range(1, W):
            for i in range(j):
                if all(row[i] <= row[j] for row in A):
                    dp[j] = max(dp[i]+1, dp[j])
        return W - max(dp)

class Solution:
    def minDeletionSize(self, A):
        m, n = len(A), len(A[0])
        dp = [1] * n
        for j in range(1, n):
            for k in range(j):
                if all(A[i][k] <= A[i][j] for i in range(m)):
                    dp[j] = max(dp[j], dp[k] + 1)
        return n - max(dp)      

class Solution:
    def minDeletionSize(self, a: List[str]) -> int:
        n,m = len(a), len(a[0])
        dp = [1 for i in range(m)]
        # dp[0] = 1
        maxx = 1
        for i in range(1, m):
            for j in range(i):
                if all(a[k][i]>=a[k][j] for k in range(n)):
                    dp[i] = max(dp[i], dp[j]+1)
                    maxx = max(maxx, dp[i])
        return m - maxx

class Solution(object):
    def minDeletionSize(self, A):
        W = len(A[0])
        dp = [1] * W
        for i in range(W-2, -1, -1):
            for j in range(i+1, W):
                if all(row[i] <= row[j] for row in A):
                    dp[i] = max(dp[i], 1 + dp[j])

        return W - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        
        l = len(A[0])
        dp = [1] * l
        
        for i in range(1, l):
            for j in range(i):
                if all(a[i] >= a[j] for a in A):
                    dp[i] = max(dp[i], dp[j]+1)
        return l-max(dp)
    
            
                
            
            
            
                    
            
            
        
        
        


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        memo = [1 for _ in range(len(A[0]))]
        for i in range(len(A[0])):
            for j in range(i):
                if all(A[k][j] <= A[k][i] for k in range(len(A))):
                    memo[i] = max(memo[i], memo[j] + 1)
        return len(A[0]) - max(memo)


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        n,m = len(A[0]),len(A)
        dp = [1]*n
        for j in range(1,n):
            for i in range(j):
                if all(A[k][i]<=A[k][j] for k in range(m)):
                    dp[j] = max(dp[j],1+dp[i])
        return n-max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        n = len(A[0])
        dp = [1] * n
        for i in range(n-2, -1, -1):
            for j in range(i+1, n):
                if all(A[k][i]<=A[k][j] for k in range(len(A))):
                    dp[i] = max(dp[i], 1+dp[j])
        return n - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        size = len(A[0])
        best = [0] * size
        best[0] = 1
        for i in range(1, size):
            best[i] = 1
            for j in range(0, i):
                if best[j] >= best[i] and self.beats(A, i, j):
                    best[i] = best[j] + 1
        
        return size - max(best)
        
        
    def beats(self, A, a, b):
        # Returns True if idx a beats idx b
        for s in A:
            if s[b] > s[a]:
                return False
            
        return True


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        
        l = len(A[0])
        dp = [1 for _ in range(l)] + [0]
        for i in range(len(dp)-1, -1, -1):
            for j in range(i+1, l):
                if all(A[k][i] <= A[k][j] for k in range(len(A))):
                    dp[i] = max(dp[i], dp[j]+1)
        
        
        return l - max(dp)

class Solution:
    def less_than(self,A,i,j):
        for r in range(len(A)):
            if ord(A[r][i]) > ord(A[r][j]):
                return False
        return True
    
    def minDeletionSize(self, A: List[str]) -> int:
        #for r in A:
        #    print(r)
        # for i in range(1,len(A[0])):
        #     print(self.less_than(A,i-1,i))
        n = len(A[0])
        dp = [ 1 for i in range(n)]
        
        for i in range(1,n):
            #print(\"i=\",i)
            j = i-1
            while(j>=0):
                #print(j,i,self.less_than(A,j,i))
                if self.less_than(A,j,i):
                    dp[i] = max(dp[i],dp[j]+1)
                j -=1
            #print(i,dp)
        
        return n-max(dp)
                       
        


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        N = len(A)
        wordLen = len(A[0])
        
        table = [1 for _ in range(wordLen)]
        
        for i in range(wordLen-2, -1, -1):
            subAnsSet = set()
            for k in range(i+1, wordLen):
                if A[0][i] <= A[0][k]:
                    subAnsSet.add(k)     
            for j in range(1, N):
                nextSubAnsSet = set()
                for k in subAnsSet:
                    if A[j][i] <= A[j][k]:
                        nextSubAnsSet.add(k)
                subAnsSet &= nextSubAnsSet
            table[i] = max([table[k]+1 for k in subAnsSet]+[1])
        return wordLen - max(table)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        def compare(i, j):
            return all(A[k][i] <= A[k][j] for k in range(len(A)))
        
        l = len(A[0])
        dp = [1 for _ in range(l)] + [0]
        for i in range(len(dp)-1, -1, -1):
            for j in range(i+1, l):
                if compare(i, j):
                    dp[i] = max(dp[i], dp[j]+1)
        
        
        return l - max(dp[i] for i in range(l))

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        m, n = len(A), len(A[0])
        dp = [0] * (n + 1)
        for i in range(n - 1, -1, -1):
            for j in range(i + 1):
                a = 1 + dp[j]
                b = 10 ** 9
                if j == 0 or all(A[k][i] >= A[k][j - 1] for k in range(m)):
                    b = dp[i + 1]
                dp[j] = min(a, b)
        return dp[0]

class Solution:
    def less_than(self,A,i,j):
        for r in range(len(A)):
            if ord(A[r][i]) > ord(A[r][j]):
                return False
        return True
    
    def minDeletionSize(self, A: List[str]) -> int:
        for r in A:
            print(r)
        # for i in range(1,len(A[0])):
        #     print(self.less_than(A,i-1,i))
        n = len(A[0])
        dp = [ 1 for i in range(n)]
        
        for i in range(1,n):
            #print(\"i=\",i)
            j = i-1
            while(j>=0):
                #print(j,i,self.less_than(A,j,i))
                if self.less_than(A,j,i):
                    dp[i] = max(dp[i],dp[j]+1)
                j -=1
            #print(i,dp)
        
        return n-max(dp)
                       
        


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        @lru_cache(None)
        def dp(i, j):
            if i == n:
                return 0
            a = 1 + dp(i + 1, j)
            b = 10 ** 9
            if j == -1 or all(A[k][i] >= A[k][j] for k in range(m)):
                b = dp(i + 1, i)
            return min(a, b)
        
        m, n = len(A), len(A[0])
        return dp(0, -1)

from functools import lru_cache


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        R, C = len(A), len(A[0])
        
        def col_lower(j1, j2):
            return all(A[i][j1] <= A[i][j2] for i in range(R))
        
        @lru_cache(None)
        def LIS(i):
            if i == 0:
                return 1
            
            return max(
                (LIS(j) for j in range(i) if col_lower(j, i)),
                default=0,
            ) + 1

        return C - max(LIS(i) for i in range(C))


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        dp = {-1: 0}
        for j in range(len(A[0])):
            new = defaultdict(lambda: 0)
            for k, v in list(dp.items()):
                if k == -1:
                    new[-1] = 0
                    new[j] = 1
                else:
                    if all(ord(A[i][k]) <= ord(A[i][j]) for i in range(len(A))):
                        new[j] = max(new[j], v + 1)
                    new[k] = max(new[k], v)
            dp = new
        
        return len(A[0]) - max(dp.values())


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        l,m = len(A),len(A[0])
        f = [i for i in range(m)]
        f[0] = 0
        for i in range(1,m):
            for j in range(0,i):
                flag = True
                for k in range(l):
                    if A[k][j] > A[k][i]:
                        flag = False
                        break
                if flag:
                    f[i] = min(f[i],f[j]+i-j-1)
            
        # print(f)
        # g = [f[i]+m-1-i for i in range(m)]
        # print(g)
        # return min(g)
        return min([f[i]+m-1-i for i in range(m)])
        
                    


class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        word_length = len(A[0])
        dp = [1] * word_length
        
        for index in range(word_length):
            for curr in range(index - 1, -1, -1):
                poss = True
                for k in range(len(A)):
                    if A[k][index] < A[k][curr]:
                        poss = False
                        break
                if poss:
                    dp[index] = max(dp[index], 1 + dp[curr])
        return word_length - max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        m, n = len(A), len(A[0])
        memo = [1] * n
        for i in range(n):
            for j in range(i):
                for k in range(m):
                    if A[k][j] > A[k][i]:
                        break
                else:
                    memo[i] = max(memo[i], memo[j] + 1)
        return n - max(memo)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        m = len(A)
        n = len(A[0])
        dp = [1 for i in range(n)]
        maxVal = 1
        
        def check(i, j):
            for k in range(m):
                if A[k][i] < A[k][j]:
                    return False
            return True
        
        for i in range(1, n):
            for j in range(i):
                if check(i, j):
                    dp[i] = max(dp[i], dp[j]+1)
            maxVal = max(maxVal, dp[i])
        
        return n - maxVal

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        dp = [1]*len(A[0])
        for j in range(1,len(A[0])):
            for k in range(j):
                isAfter = True
                for i in range(len(A)):
                    if A[i][k] > A[i][j]:
                        isAfter = False
                        break
                if isAfter:
                    dp[j] = max(dp[j],dp[k]+1)
        return len(A[0])-max(dp)

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        def printi(i,*string):
            if i==len(A[0])-1:
                print(string)
        dp = [1]*len(A[0])
        for j in range(1,len(A[0])):
            for k in range(j):
                isAfter = True
                for i in range(len(A)):
                    if A[i][k] > A[i][j]:
                        isAfter = False
                        break
                if isAfter:
                    dp[j] = max(dp[j],dp[k]+1)
        print(dp)
        return len(A[0])-max(dp)