Delete Columns to Make Sorted - Problem

You are given an array of n strings strs, all of the same length.

The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as follows:

abc
bce
cae

You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted, while column 1 ('b', 'c', 'a') is not, so you would delete column 1.

Return the number of columns that you will delete.

Input & Output

Example 1 — Basic Case
$ Input: strs = ["abc", "bce", "cae"]
Output: 1
💡 Note: Column 0: 'a','b','c' is sorted. Column 1: 'b','c','a' is not sorted (c > a). Column 2: 'c','e','e' is sorted. Delete 1 column.
Example 2 — All Sorted
$ Input: strs = ["abcdef"]
Output: 0
💡 Note: Only one string, so all columns are trivially sorted. Delete 0 columns.
Example 3 — All Unsorted
$ Input: strs = ["zyx", "wvu", "tsr"]
Output: 3
💡 Note: All columns are in descending order. Column 0: 'z','w','t', Column 1: 'y','v','s', Column 2: 'x','u','r'. Delete all 3 columns.

Constraints

  • 1 ≤ strs.length ≤ 100
  • 1 ≤ strs[i].length ≤ 1000
  • strs[i] consists of lowercase English letters

Visualization

Tap to expand
Delete Columns to Make SortedInput: ["abc", "bce", "cae"]"abc""bce""cae"Form GridabcbcecaeSorted ✓Delete ✗Sorted ✓Output: 1 (delete middle column)
Understanding the Visualization
1
Input
Array of strings: ["abc", "bce", "cae"]
2
Form Grid
Arrange strings as rows to visualize columns
3
Check Columns
Count unsorted columns that need deletion
Key Takeaway
🎯 Key Insight: A column is sorted if characters read top-to-bottom are in non-decreasing lexicographic order
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~8 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen