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.
1def findLUSlength(a: str, b: str) -> int:
2 return -1 if a == b else max(len(a), len(b))
3
4print(findLUSlength("aba", "cdc"))
This Python solution uses simple comparison to check strings for equality. The max
function determines the longest string for different inputs.
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.
1using System;
2
3class Program {
4 public static bool IsSubsequence(string s, string t) {
5 int i = 0, j = 0;
6 while (i < s.Length && j < t.Length) {
7 if (s[i] == t[j]) i++;
8 j++;
9 }
10 return i == s.Length;
11 }
12 public static int FindLUSlength(string a, string b) {
13 if (IsSubsequence(a, b) || IsSubsequence(b, a)) return -1;
14 return Math.Max(a.Length, b.Length);
15 }
16 static void Main() {
17 string a = "aba";
18 string b = "cdc";
19 Console.WriteLine(FindLUSlength(a, b));
20 }
21}
This C# approach utilizes IsSubsequence
as a helper function to ascertain the relationship between a
and b
, and returns the appropriate result.