Sponsored
Sponsored
This approach utilizes dynamic programming to identify the minimum columns to delete to make each row lexicographically sorted. The key idea is to use a dp array where dp[j] represents the length of the longest increasing subsequence of columns ending at index j.
We'll iterate over each column and compare with the previous columns to update the dp array by checking each row for their lexicographic order. We finally return the total number of columns minus the maximum value in the dp array, which gives the least number of deletions needed.
Time Complexity: O(n^2 * m), where n is the length of each string and m is the number of strings.
Space Complexity: O(n) for the dp array.
1import java.util.*;
2
3public class Solution {
4 public int minDeletionSize(String[] strs) {
5 int n = strs[0].length();
6 int[] dp = new int[n];
7 Arrays.fill(dp, 1);
8
9 for (int j = 1; j < n; ++j) {
10 for (int i = 0; i < j; ++i) {
11 boolean valid = true;
12 for (String s : strs) {
13 if (s.charAt(i) > s.charAt(j)) {
14 valid = false;
15 break;
16 }
17 }
18 if (valid) dp[j] = Math.max(dp[j], dp[i] + 1);
19 }
20 }
21 return n - Arrays.stream(dp).max().orElse(1);
22 }
23}
24
In Java, the solution employs dynamic programming with an array initialized to store subsequences' lengths. For each pair of indices, it verifies if these maintain column order across all strings. If ordered, it updates the dp array to reflect the longest subsequence found. The result is derived by subtracting this sequence length from the total column count.
This approach involves a greedy strategy where we incrementally build the sorted subset of columns. By comparing columns, we find those that necessarily break the order when removed and only retain these to maintain row order.
At each step, the algorithm compares characters in successive columns, choosing deletions based on maintaining an overall least sequence of lexicographically ordered characters per row.
Time Complexity: O(m * n), where m is the number of strings and n is the length of each string.
Space Complexity: O(1), as only constant space is used.
In this greedy C solution, we traverse each column, comparing successive characters for lexicographic order. If for any column, the order breaks, the column is marked for deletion, thereby incrementing the answer tally, which is returned as the result.