Count columns to be deleted to make each row sorted

Given an array arr[] of strings of same length, the task is to count the number of columns to be deleted so that all the rows are lexicographically sorted.


Input: arr[] = {“hello”, “geeks”}
Output: 1
Deleting column 1 (index 0)
Now both strings are sorted in lexicographical order i.e. “ello” and “eeks”.

Input: arr[] = {“xyz”, “lmn”, “pqr”}
Output: 0
All rows are already sorted lexicographically.

Approach: The idea of the problem is to find the columns to keep, instead of columns to delete. Finally we return the difference of the counted value with the length of the string.
Now, let’s say we keep the first column C1. The next column C2 we must have all rows lexicographically sorted i.e. C1[i] <= C2[i] for all valid values of i and we say that we have deleted all columns between C1 and C2.

Below is the implementation of the above approach:





# Python3 implementation of the approach
# Function to find minimum columns to be deleted
def deleteColumns(A):
    # Length of each string
    l = len(A[0])
    # Initialize dp array
    dp = [1] * l
    for i in range(l - 2, -1, -1):
        for j in range(i + 1, l):
            if all(row[i] <= row[j] for row in A):
                dp[i] = max(dp[i], 1 + dp[j])
    # Return result
    return l - max(dp)
# Driver Code
arr = ["hello", "geeks"]
# Function call to print required answer




Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Recommended Posts:

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.