Delete Columns to Make Sorted - Problem
Delete Columns to Make Sorted
Imagine you have a collection of words displayed as a grid where each word forms a row, and each column represents characters at the same position across all words. Your task is to clean up this grid by removing columns that aren't sorted in lexicographical (alphabetical) order.
For example, given
Looking at each column vertically:
• Column 0:
• Column 1:
• Column 2:
You need to count how many columns must be deleted to make all remaining columns sorted. In this case, we delete 1 column (column 1).
Imagine you have a collection of words displayed as a grid where each word forms a row, and each column represents characters at the same position across all words. Your task is to clean up this grid by removing columns that aren't sorted in lexicographical (alphabetical) order.
For example, given
["abc", "bce", "cae"], we can visualize it as:a b c
b c e
c a e
Looking at each column vertically:
• Column 0:
a → b → c ✅ (sorted)• Column 1:
b → c → a ❌ (not sorted, 'a' comes after 'c')• Column 2:
c → e → e ✅ (sorted)You need to count how many columns must be deleted to make all remaining columns sorted. In this case, we delete 1 column (column 1).
Input & Output
example_1.py — Basic Case
$
Input:
["cba", "daf", "ghi"]
›
Output:
1
💡 Note:
Column 0: c→d→g (sorted ✓), Column 1: b→a→h (not sorted ✗), Column 2: a→f→i (sorted ✓). Delete 1 column.
example_2.py — All Sorted
$
Input:
["a", "b"]
›
Output:
0
💡 Note:
Only one column with a→b, which is already sorted. No deletions needed.
example_3.py — All Unsorted
$
Input:
["zyx", "wvu", "tsr"]
›
Output:
3
💡 Note:
All columns are in descending order, so all 3 columns must be deleted.
Constraints
- 1 ≤ strs.length ≤ 1000
- 1 ≤ strs[i].length ≤ 1000
- strs[i] consists of lowercase English letters
- All strings have the same length
Visualization
Tap to expand
Understanding the Visualization
1
Form the Grid
Arrange all strings as rows to create a character grid
2
Check Each Column
For each column, scan from top to bottom checking if characters are in ascending order
3
Count Violations
Count how many columns have at least one out-of-order pair
Key Takeaway
🎯 Key Insight: We only need to scan each column once from top to bottom - the moment we find a character that's smaller than the previous one, we know that column must be deleted.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code