#522

Longest Uncommon Subsequence II

Medium
ArrayHash TableTwo PointersStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution leverages the fact that if a string is the longest, it cannot be a subsequence of any other string of equal or greater length. Thus, we can sort the strings by length and check only the longest strings for uniqueness.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the strings by length in descending order.
  2. 2Step 2: For each string, check if it is a subsequence of any other string with the same or greater length.
  3. 3Step 3: If a string is not a subsequence of any other, return its length as the longest uncommon subsequence.
solution.py11 lines
1def is_subsequence(s1, s2):
2    it = iter(s2)
3    return all(c in it for c in s1)
4
5
6def findLUSlength(strs):
7    strs.sort(key=len, reverse=True)
8    for i in range(len(strs)):
9        if all(not is_subsequence(strs[i], strs[j]) for j in range(len(strs)) if i != j):
10            return len(strs[i])
11    return -1

Complexity note: The time complexity remains O(n²) due to the nested loops for checking subsequences. However, sorting the strings adds an additional O(n log n) factor, which is dominated by the subsequence checks. The space complexity is O(1) since we are not using any extra space beyond variables.

  • 1A string can only be an uncommon subsequence if it is not a subsequence of any other string in the array.
  • 2Sorting the strings by length helps in efficiently finding the longest uncommon subsequence.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.