I was trying to solve this hiring contest problem (now closed)
Lexicographic Rows
You are given a matrix of characters. In one operation you can remove a column of the matrix. You can perform as many operations as you want. Your task is to make the final matrix interesting i.e. the string formed by the characters of row is lexicographically smaller or equal to the string formed by the characters of the row. You need to use minimum number of operations possible. An empty matrix is always a interesting matrix.
Input
The first line contains two integers and . The next lines contain letters each.
Output
In the output, you need to print the minimum number of operations to make the matrix interesting.
Constraints
There are only lowercase English alphabets as characters in the input.
Sample Input
3 3
cfg
agk
dlm
Sample Output
1
Explanation
Delete the first column to make the matrix interesting.
I'm pretty convinced this is a DP problem. I was having difficulties finding the optimal subproblem though. I managed to pass only a couple of test cases
I defined dp[i][j]
as the minimum number of the columns to be removed to have an interesting matrix.
And for every character input[i][j]
there are two possibilities.
- if the previous entry is lexicographically valid we can take
dp[i][j - 1]
and the current input isn't going to change anything. - else we check if the
input[i -1][j]
andinput[i][j]
if they are in the correct order we considerdp[i][j - 1]
else this column is invalid too so we add1
todp[i][j-1]
My soln. code
int n, m;
cin >> n >> m;
vector<string> input(n);
for (int i = 0; i < n; ++i) {
string temp = "";
for (int j = 0; j < m; ++j) {
char c;
cin >> c;
temp = temp + c;
}
input[i] = temp;
}
vector<vector<int> > dp(n, vector<int>(m, 0));
for (int i = 1; i < n; ++i) {
for (int j = 1; j < m; ++j) {
//Left is valid
if (input[i - 1][j - 1] < input[i][j - 1]) {
dp[i][j] = dp[i][j - 1];
}
else {
//Current is valid
if (input[i - 1][j] <= input[i][j]) {
dp[i][j] = dp[i][j - 1];
}
else {
dp[i][j] = dp[i][j - 1] + 1;
}
}
}
}
cout << dp[n - 1][m - 1] << endl;