Leetcode #955: Delete Columns to Make Sorted II
In this guide, we solve Leetcode #955 Delete Columns to Make Sorted II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, Array, String
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: strs = ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, strs = ["a", "b", "c"].
Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
Python Solution
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
n = len(strs)
m = len(strs[0])
st = [False] * (n - 1)
ans = 0
for j in range(m):
must_del = False
for i in range(n - 1):
if not st[i] and strs[i][j] > strs[i + 1][j]:
must_del = True
break
if must_del:
ans += 1
else:
for i in range(n - 1):
if not st[i] and strs[i][j] < strs[i + 1][j]:
st[i] = True
return ans
Complexity
The time complexity is and the space complexity is , where and are the length of the string array and the length of each string, respectively. The space complexity is , where and are the length of the string array and the length of each string, respectively.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.