Delete Columns to Make Sorted III - 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.

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.

Input & Output

Example 1 — Basic Case
$ Input: strs = ["cab","daf","ghi"]
Output: 1
💡 Note: We can delete column 0. After deletion: ["ab","af","hi"]. Each string is now lexicographically sorted: a≤b, a≤f, h≤i.
Example 2 — No Deletions Needed
$ Input: strs = ["abc","def","ghi"]
Output: 0
💡 Note: All strings are already lexicographically sorted. No columns need to be deleted.
Example 3 — Multiple Deletions
$ Input: strs = ["zyx","wvu","tsr"]
Output: 2
💡 Note: Keep only the last column. After deleting columns 0 and 1: ["x","u","r"]. Each string has only one character, so they're sorted.

Constraints

  • n == strs.length
  • 1 ≤ n ≤ 100
  • 1 ≤ strs[i].length ≤ 100
  • strs[i] consists of lowercase English letters

Visualization

Tap to expand
Delete Columns to Make Sorted III INPUT String Array (3 strings, length 3) strs[0]: c a b strs[1]: d a f strs[2]: g h i col 0 col 1 col 2 Delete Keep Input Values strs = ["cab","daf","ghi"] n = 3 strings, length = 3 ALGORITHM STEPS 1 Define DP State dp[i] = max columns kept ending at column i 2 Check Column Pairs For j < i, check if col j can precede col i 3 Lexicographic Check All rows: str[k][j] <= str[k][i] must hold for transition 4 Calculate Answer answer = n - max(dp[i]) Min deletions needed DP Table col: 0 1 2 dp[]: 1 1 2 max(dp) = 2, answer = 3-2 = 1 FINAL RESULT After deleting column 0: "cab" --> "ab" "daf" --> "af" "ghi" --> "hi" Lexicographic Check: "ab": a < b [OK] "af": a < f [OK] "hi": h < i [OK] OUTPUT 1 Key Insight: This is a Longest Increasing Subsequence (LIS) variant. Instead of finding LIS in numbers, we find the longest sequence of columns where each column is lexicographically greater than or equal to the previous across ALL rows. Time: O(n * m^2), Space: O(m) where m = string length. TutorialsPoint - Delete Columns to Make Sorted III | Optimal DP Solution
Asked in
Google 25 Facebook 18
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen