#955

Delete Columns to Make Sorted II

Medium
ArrayStringGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(m)
💡

Intuition

Time O(n * m)Space O(m)

The optimal approach uses a greedy strategy to determine which columns to delete by comparing adjacent strings. If a column causes disorder, we mark it for deletion. This avoids the need for generating combinations and checking all possibilities.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a set to keep track of columns to delete.
  2. 2Step 2: Iterate through the strings, comparing each string with the next one.
  3. 3Step 3: For each pair of strings, check each column. If the current column causes disorder, mark it for deletion.
  4. 4Step 4: Return the size of the deletion set as the result.
solution.py12 lines
1# Full working Python code
2
3def minDeletionSize(strs):
4    to_delete = set()
5    n = len(strs)
6    m = len(strs[0])
7    for j in range(m):
8        for i in range(n - 1):
9            if strs[i][j] > strs[i + 1][j]:
10                to_delete.add(j)
11                break
12    return len(to_delete)

Complexity note: The time complexity is O(n * m) because we iterate through each character in the strings, comparing adjacent strings, leading to a linear scan of the characters.

  • 1Understanding lexicographic order is crucial.
  • 2Greedy approaches can often simplify complex problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.