Delete Columns to Make Sorted III — LeetCode 960 Python Solution
- Problem
- #960
- Pattern
- Dynamic Programming
- Reading time
- 2 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 = ["babca","bbazb"]
- Output
- 3
- Explanation
- After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].
Python solution
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
n = len(strs[0])
f = [1] * n
for i in range(n):
for j in range(i):
if all(s[j] <= s[i] for s in strs):
f[i] = max(f[i], f[j] + 1)
return n - max(f)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times m) |
| Space | O(n), where n is the length of each string in the array \textit{strs}, and m is the number of strings in the array auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 960. Delete Columns to Make Sorted III is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 960. Delete Columns to Make Sorted III?
- LeetCode 960. Delete Columns to Make Sorted III is rated Hard on LeetCode.
- What is the time complexity of LeetCode 960. Delete Columns to Make Sorted III?
- The Python solution on this page runs in O(n^2 \times m).
- What is the space complexity of LeetCode 960. Delete Columns to Make Sorted III?
- The Python solution on this page uses O(n), where n is the length of each string in the array \textit{strs}, and m is the number of strings in the array auxiliary space.
- What topics does LeetCode 960. Delete Columns to Make Sorted III cover?
- LeetCode 960. Delete Columns to Make Sorted III is tagged Array, String and Dynamic Programming on LeetCode.