Last Updated: 8 Apr, 2021

Count unsorted columns

Easy
Asked in company
Amazon

Problem statement

You are given an array ‘STRINGS’ having ‘N’ number of strings. The strings are assumed to be arranged such that there is one string in one line.

You need to return the number of columns that are not sorted lexicographically.

Note:
The length of all the strings in the array is the same.
For Example:
If the given array is [ “bde”, “dcf”, “gat” ], then it can be assumed to arranged as
bde
dcf 
gat 

Now the ‘0-th’ column (‘b’, ‘d’, ‘e’) and ‘2-th’ column ( ‘e’, ‘f’, ‘t’ ) are lexicographically sorted but the ‘1-st’ column ( ‘d’, ‘c’, ‘a’ ) is not sorted lexicographically. So you need to return 1.
Input Format:
The first line contains a single integer ‘T’, denoting the number of test cases.

Each test case’s first line contains ‘N’, denoting the number of strings in the array.

The next ‘N’ lines contain strings of the same length that make up ‘Strings’.
Output Format:
For each test case, print a single line containing a single integer denoting the number of columns that are not sorted lexicographically.

The output of each test case will be printed in a separated line.
Note:
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
1 <= N <= 100
1 <= L <= 10 ^ 3

Where ‘T’ is the number of test cases, ‘n’ is the number of strings, and ‘L’  is each string’s length.

Time limit: 1 sec.

Approaches

01 Approach

The simple idea is to traverse through every column of strings. For each column, check if it is lexicographically sorted or not. If not, increment the count by one.

 

Algorithm

 

  • Initialize a variable ‘count’ to store the result.
  • Run a loop col : 0 to (length of string  - 1). to traverse all the columns.
    • Run a loop row: 0 to N - 2  to iterate through all characters of a column.
    • If char at string[ row ][ col ] > string[ row + 1 ][ col ]
      • Increment ‘count’ by ‘1’.
  • Return ‘count’.