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 Sorted INPUT String Array as Grid: Col 0 Col 1 Col 2 a b c "abc" b c e "bce" c a e "cae" SORTED NOT SORTED Input: ["abc", "bce", "cae"] a<b<c b<c>a c<e=e (lexicographic order) ALGORITHM STEPS 1 Initialize Counter Set deleteCount = 0 2 Iterate Columns For each column j (0 to 2) 3 Check Sorted Order Compare strs[i][j] with strs[i+1][j] for all rows 4 Count Unsorted If any pair violates order, increment deleteCount++ Column Check Results: Col 0: a<b<c OK Col 1: b<c but c>a DELETE Col 2: c<e, e=e OK deleteCount = 1 FINAL RESULT Columns to Delete: Column 1 Remaining Sorted Columns: Col 0 Col 2 Output: 1 1 column deleted (Col 1) 2 columns remain sorted Key Insight: Single Pass Optimized: For each column, scan top-to-bottom comparing adjacent characters. If strs[i][j] > strs[i+1][j] at any row, the column is unsorted. Break early and count it. Time: O(n * m) where n = number of strings, m = string length. Space: O(1) - constant extra space. TutorialsPoint - Delete Columns to Make Sorted | Single Pass Optimized
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