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 IIIOriginal Strings"cab""daf""ghi"Not all sorted!Delete Column 0cabdafghiResult"ab" ✓"af" ✓"hi" ✓All strings sorted!Minimum deletions needed: 1 columnGoal: Keep maximum columns while maintaining lexicographic order in all strings
Understanding the Visualization
1
Input Analysis
Array of strings with same length, need all rows sorted
2
Column Selection
Find which columns to keep for maintaining order
3
Minimum Deletions
Calculate minimum columns to delete
Key Takeaway
🎯 Key Insight: Find the longest subsequence of columns that keeps all strings sorted, then delete the rest
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