Problem
You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is lexicographically later as you go down each row. It does not matter whether each row itself is ordered lexicographically.
For example, given the following table:
|
|
This is not ordered because of the a in the center. We can remove the second column to make it ordered:
|
|
So your function should return 1, since we only needed to remove 1 column.
As another example, given the following table:
|
|
Your function should return 0, since the rows are already ordered (there’s only one row).
As another example, given the following table:
|
|
Your function should return 3, since we would need to remove all the columns to order it.
Examples
Solution
Method 1 - Iteration
Plan
- We will iterate through each column of the matrix.
- For each column, we will check if the column is sorted lexicographically.
- If a column is not sorted, we will mark it for removal.
- At the end, we will return the number of columns marked for removal.
Implementation
- Initialization:
- We will initialize a counter
count
to keep track of the number of columns to be removed.
- We will initialize a counter
- Iterate through each column:
- For each column, starting from the top row, check if the current element is lexicographically greater than or equal to the element in the previous row.
- If we find any element which is smaller than the previous row’s element in the same column, we increment our counter and mark this column for removal.
- Return the result:
- Finally, return the count of columns that are not lexicographically sorted.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m*n)
wherem
is number of rows andn
is number of columns - 🧺 Space complexity:
O(1)