This approach takes advantage of the fact that if two strings are identical, there are no uncommon subsequences. If they are different, the longest uncommon subsequence is the longest string itself.
a
is equal to b
, return -1 because all subsequences of a
are subsequences of b
and vice versa.a
is not equal to b
, return the maximum length of a
or b
since the longer string itself cannot be a subsequence of the other.Time Complexity: O(n) where n is the length of the strings, due to the string comparison.
Space Complexity: O(1), no additional space is needed.
1using System;
2
3class Program {
4 public static int FindLUSlength(string a, string b) {
5 return a == b ? -1 : Math.Max(a.Length, b.Length);
6 }
7
8 static void Main() {
9 string a = "aba";
10 string b = "cdc";
11 Console.WriteLine(FindLUSlength(a, b));
12 }
13}
This C# solution uses the equality operator ==
for strings and Math.Max
to calculate the desired result.
Another approach is to analyze the problem by considering the entire strings as potential subsequences and determine their existence in the other string.
Time Complexity: O(n + m) where n and m are the lengths of the strings.
Space Complexity: O(1), since no additional structures are employed.
1def is_subsequence(s, t):
2 it = iter(t)
3 return all(c in it for c in s)
4
5def findLUSlength(a: str, b: str) -> int:
6 if is_subsequence(a, b) or is_subsequence(b, a):
7 return -1
8 return max(len(a), len(b))
9
10print(findLUSlength("aba", "cdc"))
The Python solution leverages a function is_subsequence
using iterators to detect subsequences. It applies this for both a
and b
, then returns appropriately.