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.

**Examples:**

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` `print` `(deleteColumns(arr))` |

**Output:**

1

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. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**

In case you wish to attend live classes with industry experts, please refer **Geeks Classes Live**