Count no. of columns that are not sorted in increasing order

Given an array A of N lowercase letter strings of the same length. The task is to find the count of columns that are not sorted in increasing order.

Examples:

Input: A = ["cba", "dah", "ghi"]
Output: 1
2nd Column ["b", "a", "h"] is not sorted in increasing order.

Input: A = ["zyx", "wvu", "tsr"]
Output: 3
All columns are not sorted in increasing order.

Approach: Traverse each column one by one and check if the next element is greater than the previous element in the same column. If not the increment the countOfCol by 1 and keep traversing till all the columns get traversed. Print the value of countOfCol.

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to count the unsorted columns
def countUnsorted(A):
  
    countOfCol = 0
  
    for col in zip(*A):
        if any(col[i] > col[i + 1] for i in range(len(col) - 1)):
            countOfCol += 1
  
    return countOfCol
  
# Driver code
A = ["cba", "daf", "ghi"]
print(countUnsorted(A))

chevron_right


Output:

1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.