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.
staticIEnumerable<string> GetColumns(List<string> A)
{
intmaxLength = A[0].Length;
for(inti = 0; i < maxLength; i++) {
stringcolumn = "";
foreach(stringrow inA)
{
if(i < row.Length)
column += row[i];
}
yieldreturncolumn;
}
}
staticvoidMain(string[] args)
{
List<string> A
= newList<string>{ "cba", "daf", "ghi"};
Console.WriteLine(CountUnsorted(A));
}
}
Javascript
// Javascript code addition
// Function to count the unsorted columns
functioncountUnsorted(A) {
let countOfCol = 0;
for(let col of A[0].split("").keys()) {
for(let row = 0; row < A.length - 1; row++) {
if(A[row][col] > A[row + 1][col]) {
countOfCol++;
break;
}
}
}
returncountOfCol;
}
// Driver code
let A = ["cba", "daf", "ghi"];
console.log(countUnsorted(A));
// The code is contributed by Nidhi goel.
Output
1
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!