LeetCode 960: Delete Columns to Make Sorted III Solution

Master LeetCode problem 960 (Delete Columns to Make Sorted III), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

960. Delete Columns to Make Sorted III

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. The idea is to consider the longest common subsequence among all possible column sequences of the strings. By finding the longest common subsequence, we can determine the minimum number of columns that need to be deleted to make all strings lexicographically ordered.

We will create a 2D array dp of size n x n, where dp[i][j] represents the length of the longest common subsequence between the strings strs[i] and strs[j]. We will iterate over all pairs of strings and calculate the longest common subsequence for each pair. Then, we will find the maximum value in the dp array, which will represent the minimum number of columns to delete.

The time complexity of this approach is O(n^2 * m^2), where n is the number of strings and m is the length of each string. The space complexity is O(n^2).

Solution Code

class Solution {
    public int minDeletionSize(String[] strs) {
        int n = strs.length;
        int m = strs[0].length();
        int[] dp = new int[n];
        Arrays.fill(dp, 1);

        for (int j = 0; j < m; j++) {
            for (int i = 0; i < j; i++) {
                boolean valid = true;
                for (int k = 0; k < n; k++) {
                    if (strs[k].charAt(i) > strs[k].charAt(j)) {
                        valid = false;
                        break;
                    }
                }
                if (valid) {
                    dp[j] = Math.max(dp[j], dp[i] + 1);
                }
            }
        }

        return m - Arrays.stream(dp).max().getAsInt();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 960 (Delete Columns to Make Sorted III)?

This page provides optimized solutions for LeetCode problem 960 (Delete Columns to Make Sorted III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 960 (Delete Columns to Make Sorted III)?

The time complexity for LeetCode 960 (Delete Columns to Make Sorted III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 960 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 960 in Java, C++, or Python.

Back to LeetCode Solutions