LeetCode 522: Longest Uncommon Subsequence II Solution

Master LeetCode problem 522 (Longest Uncommon Subsequence II), a medium 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.

522. Longest Uncommon Subsequence II

Problem Explanation

Explanation:

To solve this problem, we can iterate through each pair of strings in the input array and check if one string is a subsequence of the other. If a string is not a subsequence of any other string, we can return its length as the longest uncommon subsequence. If all strings are subsequences of each other, we return -1.

  1. Create a helper method to check if one string is a subsequence of another string.
  2. Iterate through each pair of strings in the input array.
  3. For each pair, check if one string is a subsequence of the other.
  4. If a string is not a subsequence of any other string, return its length as the longest uncommon subsequence.
  5. If no such string is found, return -1.

Time Complexity: O(n^2 * m) where n is the number of strings and m is the maximum length of a string.
Space Complexity: O(1)

:

Solution Code

class Solution {
    public int findLUSlength(String[] strs) {
        int longestUncommon = -1;
        for (int i = 0; i < strs.length; i++) {
            boolean isUncommon = true;
            for (int j = 0; j < strs.length; j++) {
                if (i != j && isSubsequence(strs[i], strs[j])) {
                    isUncommon = false;
                    break;
                }
            }
            if (isUncommon) {
                longestUncommon = Math.max(longestUncommon, strs[i].length());
            }
        }
        return longestUncommon;
    }
    
    private boolean isSubsequence(String a, String b) {
        int i = 0, j = 0;
        while (i < a.length() && j < b.length()) {
            if (a.charAt(i) == b.charAt(j)) {
                i++;
            }
            j++;
        }
        return i == a.length();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 522 (Longest Uncommon Subsequence II)?

This page provides optimized solutions for LeetCode problem 522 (Longest Uncommon Subsequence II) 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 522 (Longest Uncommon Subsequence II)?

The time complexity for LeetCode 522 (Longest Uncommon Subsequence II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 522 on DevExCode?

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

Back to LeetCode Solutions