Ctrl K

Drop Columns to Keep Rows Sorted

Medium
You get a list words of strings that all have the same length. Picture them written one under another like a table: each words[i] is a row, and the characters at the same position across all words form a column. You may cross out any set of columns; a crossed-out position is removed from every word at once. For example, crossing out columns 0 and 3 in ['bread', 'flame'] leaves ['rea', 'lae']. After crossing out, the words must be in alphabetical order from top to bottom: words[0] <= words[1] <= ... <= words[n - 1]. Return the smallest number of columns you have to cross out to achieve that. Note that the letters inside a single word do not need to be sorted; only the order of the words matters.
Example 1
words=['bd', 'ac', 'ca'] → 2

Right now bd > ac. Dropping only the first column leaves d, c, a; dropping only the second leaves b, a, c. Neither is sorted, so both columns go, leaving three empty strings, which are trivially in order. The answer is 2.

Example 2
words=['cat', 'cog', 'dab'] → 0

The rows are already in alphabetical order: cat ≤ cog ≤ dab. Nothing needs to be dropped.

Example 3
words=['xay', 'xbx', 'ycz'] → 0

The first column x, x, y leaves the first two rows tied; the second column settles them with a < b. After that the third column (y > x) no longer matters and can stay.

Constraints
  • 1 ≤ len(words) ≤ 100
  • 1 ≤ len(words[i]) ≤ 100
  • All words have the same length
  • Words consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Number From Pieces MediumSmallest Up-Down Sequence MediumRing of Flippable Words MediumRound Prices to a Total MediumBead String Without Twins Medium
loading Python…
Input
words=['bd', 'ac', 'ca']
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 197 tests on the server, hidden ones included.