Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

522. Longest Uncommon Subsequence II

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)

:

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();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.