Delete Columns to Make Sorted III — LeetCode 960 Python Solution

HardArrayStringDynamic Programming
Problem
#960
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n^2 \times m)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview