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.
1#include <stdio.h>
2#include <string.h>
3
4int findLUSlength(char * a, char * b) {
5 return strcmp(a, b) == 0 ? -1 : (strlen(a) > strlen(b) ? strlen(a) : strlen(b));
6}
7
8int main() {
9 char a[] = "aba";
10 char b[] = "cdc";
11 printf("%d\n", findLUSlength(a, b));
12 return 0;
13}
This C solution uses the standard library's strcmp
function to check for string equality. If the strings are equal, it returns -1. Otherwise, it uses the strlen
function to find the length of the longest string and returns that as the length of the longest uncommon subsequence.
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.
1function isSubsequence(s, t) {
2 let i = 0, j = 0;
3 while (i < s.length && j < t.length) {
4 if (s[i] === t[j]) i++;
5 j++;
6 }
7 return i === s.length;
8}
9
10function findLUSlength(a, b) {
11 if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
12 return Math.max(a.length, b.length);
13}
14
15console.log(findLUSlength("aba", "cdc"));
The JavaScript solution defines a function isSubsequence
to check if one string is a subsequence of another, then applies it accordingly to compute the result.