Longest Uncommon Subsequence II Problem
Description
LeetCode Problem 522.
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.
- For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
Example 1:
Input: strs = ["aba","cdc","eae"]
Output: 3
Example 2:
Input: strs = ["aaa","aaa","aa"]
Output: -1
Constraints:
- 2 <= strs.length <= 50
- 1 <= strs[i].length <= 10
- strs[i] consists of lowercase English letters.
Solution
Approach: Check Each Whole String
We never need to look at proper subsequences: only the whole strings of strs can be the answer.
Suppose t is an uncommon subsequence, taken from strs[i]. Then strs[i] itself is uncommon too: if strs[i] were a subsequence of some other string, then t, being a subsequence of strs[i], would be a subsequence of that string as well. And strs[i] is at least as long as t. So the longest uncommon subsequence, if one exists, is one of the strings in the list.
- For each
candidate = strs[i], check whether it is a subsequence of any other stringstrs[j](j != i). - If it is a subsequence of none of them, it is uncommon: update the answer with its length.
- Return the longest such length, or -1 if no string qualified.
To test whether small is a subsequence of big, walk through big with a pointer into small and move the pointer each time the characters match; small is a subsequence when the pointer reaches its end.
Duplicates are the tricky part: compare by index (j != i), not by value. In Example 2 the two copies of "aaa" are each a subsequence of the other, and "aa" is a subsequence of "aaa", so the answer is -1.
Complexity: O(n2 · L) time and O(1) extra space, where n is the number of strings and L is the length of the longest one.
class Solution:
def findLUSlength(self, strs: List[str]) -> int:
def is_subsequence(small: str, big: str) -> bool:
matched = 0 # how many characters of small have been found in big so far
for ch in big:
if matched < len(small) and small[matched] == ch:
matched += 1
return matched == len(small)
best = -1
for i, candidate in enumerate(strs):
# The candidate works if it is not a subsequence of any other string.
uncommon = True
for j, other in enumerate(strs):
if i != j and is_subsequence(candidate, other):
uncommon = False
break
if uncommon:
best = max(best, len(candidate))
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.