Delete Columns to Make Sorted III - Problem
You are given an array of n strings strs, all of the same length. Your goal is to find the minimum number of columns to delete so that after deletion, every remaining string is lexicographically sorted.
What does this mean? When we delete columns at certain indices, we remove those characters from all strings. The resulting strings must have their characters in non-decreasing order (sorted alphabetically).
Example: If we have strs = ["abcdef", "uvwxyz"] and delete columns at indices {0, 2, 3}, we get ["bef", "vyz"]. Both strings are now sorted: b ≤ e ≤ f and v ≤ y ≤ z.
The challenge: Find the minimum number of columns to delete to achieve this for all strings simultaneously.
Input & Output
example_1.py — Basic Case
$
Input:
strs = ["babca", "bbazb"]
›
Output:
3
💡 Note:
After deleting columns 0, 1, and 4, the remaining strings are ["bc", "az"] where both are sorted: b ≤ c and a ≤ z. This is the minimum number of deletions needed.
example_2.py — Already Sorted
$
Input:
strs = ["eddbca", "gfhkba"]
›
Output:
4
💡 Note:
We need to delete 4 columns to make both strings sorted. One optimal solution is to keep columns that form ["dd", "gf"] after appropriate deletions.
example_3.py — Single Character
$
Input:
strs = ["ghi", "def", "abc"]
›
Output:
0
💡 Note:
Each string is already sorted individually (single characters are trivially sorted), so no deletions are needed.
Constraints
- 1 ≤ strs.length ≤ 100
- 1 ≤ strs[i].length ≤ 100
- strs[i] consists of lowercase English letters
- All strings have the same length
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Columns
Examine each column to see which ones can form valid increasing sequences
2
Build DP Table
For each column, find the longest valid sequence ending at that position
3
Find Maximum Keep
Identify the longest subsequence of columns that maintains sorting for all rows
4
Calculate Deletions
Subtract the maximum keepable columns from total columns
Key Takeaway
🎯 Key Insight: Transform the "minimum deletions" problem into finding the "maximum columns to keep" using dynamic programming - this avoids exponential search and gives us the optimal O(m²n) solution.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code