Delete Columns to Make Sorted II — LeetCode 955 Python Solution
- Problem
- #955
- Pattern
- Greedy
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- strs = ["ca","bb","ac"]
- Output
- 1
- Explanation
- After deleting the first column, strs = ["a", "b", "c"].
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times m) |
| Space | O(n), where n and m are the length of the string array and the length of each string, respectively auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 955. Delete Columns to Make Sorted II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 955. Delete Columns to Make Sorted II?
- LeetCode 955. Delete Columns to Make Sorted II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 955. Delete Columns to Make Sorted II?
- The Python solution on this page runs in O(n \times m).
- What is the space complexity of LeetCode 955. Delete Columns to Make Sorted II?
- The Python solution on this page uses O(n), where n and m are the length of the string array and the length of each string, respectively auxiliary space.
- What topics does LeetCode 955. Delete Columns to Make Sorted II cover?
- LeetCode 955. Delete Columns to Make Sorted II is tagged Greedy, Array and String on LeetCode.