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.
1function findLUSlength(a, b) {
2 return a === b ? -1 : Math.max(a.length, b.length);
3}
4
5console.log(findLUSlength("aba", "cdc"));
This JavaScript code compares strings using ===
and computes the length using Math.max
.
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.
1#include <stdio.h>
2#include <string.h>
3
4int isSubsequence(char *s, char *t) {
5 int i = 0, j = 0;
6 while (i < strlen(s) && j < strlen(t)) {
7 if (s[i] == t[j]) i++;
8 j++;
9 }
10 return i == strlen(s);
11}
12
13int findLUSlength(char *a, char *b) {
14 if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
15 return strlen(a) > strlen(b) ? strlen(a) : strlen(b);
16}
17
18int main() {
19 char a[] = "aba";
20 char b[] = "cdc";
21 printf("%d\n", findLUSlength(a, b));
22 return 0;
23}
This solution defines a helper function isSubsequence
that checks if one string is a subsequence of another using two pointers. It then uses this helper in findLUSlength
to check the relations between a
and b
.