Delete Columns to Make Sorted II - Problem

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

We may choose any deletion indices, and we delete all the characters in those indices for each string.

For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"].

Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]).

Return the minimum possible value of answer.length.

Input & Output

Example 1 — Basic Case
$ Input: strs = ["ca", "bb", "ac"]
Output: 1
💡 Note: Delete column 0: "ca"→"a", "bb"→"b", "ac"→"c". Result ["a","b","c"] is sorted. Only 1 deletion needed.
Example 2 — No Deletions Needed
$ Input: strs = ["xc", "yb", "za"]
Output: 0
💡 Note: Already lexicographically sorted: "xc" <= "yb" <= "za". No deletions needed.
Example 3 — Multiple Deletions
$ Input: strs = ["zyx", "wvu", "tsr"]
Output: 3
💡 Note: Must delete all columns since each column is in reverse order. After deleting all, get ["","",""] which is sorted.

Constraints

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

Visualization

Tap to expand
Delete Columns to Make Sorted II INPUT String Array (strs): strs[0] = " c a " strs[1] = " b b " strs[2] = " a c " col 0 col 1 Goal: Find min deletions to make strs lexicographically sorted (strs[0] <= strs[1] <= strs[2]) ALGORITHM STEPS 1 Check Column 0 c, b, a -- NOT sorted! (c > b > a is wrong) 2 Delete Column 0 Must delete to fix order deletions = 1 3 Check Column 1 a, b, c -- IS sorted! (a < b < c is correct) 4 Keep Column 1 Column maintains order Result: ["a", "b", "c"] Greedy Strategy: Process columns left to right Delete only if it breaks order Track "settled" pairs FINAL RESULT Before: ["ca", "bb", "ac"] NOT sorted (ca > bb -- wrong!) After deleting col 0: ["a", "b", "c"] IS sorted - OK (a < b < c) OUTPUT 1 Key Insight: Greedy column selection: For each column, check if keeping it maintains lexicographic order. Once a pair of adjacent strings has strict inequality (str[i] < str[i+1]), they are "settled" and future columns cannot break their order. Only delete columns that cause violations. TutorialsPoint - Delete Columns to Make Sorted II | Greedy Column-by-Column Approach
Asked in
Google 25 Facebook 18 Amazon 12
28.4K Views
Medium Frequency
~25 min Avg. Time
892 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