A remote seed vault stamps every incoming batch with a fixed-length alphanumeric code and appends it to the ledger strictly in arrival order. The ledger's retrieval scanner checks the codes one character position at a time: for a single position (the same position across every code), it reads down the ledger from the first entry to the last and requires that character to never decrease. A stamping defect can make one or more positions violate this — at that position, some later entry's character comes before some earlier entry's character in ordinary character order. Before trusting the scanner, the vault keeper must strike every defective position out of the ledger entirely, removing that same position from every single code, at a cost of one unit of restamping effort per position struck out. A position may be kept only if, read from the first entry down to the last, its characters never decrease; whether a position may be kept does not depend on any other position.
Determine the minimum number of character positions the keeper must strike out so that every remaining position is non-decreasing from the first ledger entry to the last.
Line 1: two integers n and L — the number of ledger entries and the fixed code length. Next n lines: one code each, a string of exactly L characters, each a lowercase English letter or a digit.
Print a single integer: the minimum number of character positions that must be struck out.
Example 1
Input
3 2 ca bb ac
Expected
1
Explanation
Position 0 read top to bottom is 'c','b','a', which decreases from the first entry to the second ('c'>'b'), so it is defective and must be struck out. Position 1 read top to bottom is 'a','b','c', which never decreases, so it can be kept. Only 1 position must be struck out.
Example 2
Input
3 3 zyx wvu tsr
Expected
3
Explanation
Position 0 read top to bottom is 'z','w','t' (strictly decreasing), position 1 is 'y','v','s' (strictly decreasing), and position 2 is 'x','u','r' (strictly decreasing). All three positions are defective, so all 3 must be struck out.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →