Leetcode 955: Delete Columns to Make Sorted II

grid47
grid47
Exploring patterns and algorithms
Aug 3, 2024 6 min read

You are given an array of strings, where each string is of the same length. You are allowed to delete any number of columns, and after deleting the selected columns, the remaining strings should be in lexicographically non-decreasing order. Your task is to determine the minimum number of columns that must be deleted to achieve this order.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of n strings, each string having the same length.
Example: Input: strs = ["ab","ac","bb"]
Constraints:
• 1 <= strs.length <= 100
• 1 <= strs[i].length <= 100
• strs[i] consists of lowercase English letters.
Output: The output should be an integer representing the minimum number of columns that need to be deleted to make the array of strings lexicographically ordered.
Example: Output: 1
Constraints:
• The output is an integer.
Goal: The goal is to minimize the number of columns that need to be deleted while ensuring the remaining strings are in lexicographically non-decreasing order.
Steps:
• 1. Initialize a counter to track the number of deletions.
• 2. Traverse through each column and check if the current column violates the lexicographical order between adjacent strings.
• 3. If a violation is found, increment the deletion counter and skip further checks for that column.
• 4. After checking each column, return the counter as the minimum number of deletions required.
Goal: The array will have at least one string and can have up to 100 strings, with each string being at most 100 characters long.
Steps:
• The input will always have strings of the same length.
• The number of strings will be between 1 and 100.
• The length of each string will be between 1 and 100.
• All characters in the strings are lowercase English letters.
Assumptions:
• All input strings are valid and consist only of lowercase English letters.
• The length of all strings is the same.
Input: Input: strs = ["ab","ac","bb"]
Explanation: In this case, deleting the second column (index 1) results in the array ["a", "c", "b"], which is lexicographically ordered.

Input: Input: strs = ["dc","ba","za"]
Explanation: In this case, no deletions are required since the array is already in lexicographic order.

Input: Input: strs = ["zyx","wvu","tsr"]
Explanation: Here, all columns violate the lexicographic order, so all columns must be deleted, resulting in an answer of 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus