
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete Columns to Make Sorted in Python
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 −
Example
class Solution: def minDeletionSize(self, A): return sum([1-(sorted(col)==list(col)) for col in zip(*A)]) ob = Solution() print(ob.minDeletionSize(["cba","daf","ghi"]))
Input
["cba","daf","ghi"]
Output
1