Skip to main content
Back to problems
#960
Hard Algorithms

Delete columns to make sorted iii

Array String Dynamic Programming
72.7% acceptance
Feb 25, 2026
868
31
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. For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"]. Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_deletion_size(strs: Vec<String>) -> i32 {
    let strs: Vec<Vec<u8>> = strs.iter().map(|s| s.bytes().collect()).collect();
    let cols = strs[0].len();
    let n = strs.len();
    // dp[j] = max columns we can keep ending at column j
    let mut dp = vec![1usize; cols];
    for j in 1..cols {
      for i in 0..j {
        // Can we keep col i followed by col j?
        if (0..n).all(|r| strs[r][i] <= strs[r][j]) {
          dp[j] = dp[j].max(dp[i] + 1);
        }
      }
    }
    (cols - dp.iter().max().copied().unwrap_or(0)) as i32
  }
}