Delete Columns to Make Sorted in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of N lowercase letter strings, the array name is A, all strings are of same length. Now, we can choose any set of deletion indices, and for each string, we delete all the characters in those indices.

As an example, if we have an array A like ["abcdef","uvwxyz"] and deletion indices are {0, 2, 3}, then the final array after deletions will be ["bef", "vyz"], and the remaining columns of A are ["b","v"], ["e","y"], and ["f","z"].

Suppose we chose a set of deletion indices D like after deletions, each remaining column in A is in non-decreasing sorted order. We have to find the minimum possible value of the length of D.

So, if the input is like ["cba","daf","ghi"], then the output will be 1, this is because after choosing D = {1}, then each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order. And if we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order.

To solve this, we will follow these steps −

  • A = make a matrix by taking strings from the array, and separate characters into different column
  • B = new empty list
  • for col in A, do
    • if col is already sorted then insert 0 into B
    • otherwise insert 1 into B
  • return the sum of all elements in B

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def minDeletionSize(self, A):
      return sum([1-(sorted(col)==list(col)) for col in zip(*A)])
ob = Solution()




Updated on 06-Jul-2020 09:13:15