VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-uncommon-subsequence/

⇱ Longest Uncommon Subsequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Uncommon Subsequence

Last Updated : 16 Oct, 2023

Given two strings, find the length of longest uncommon subsequence of the two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings which is not a subsequence of other strings. 

Examples:

Input : "abcd", "abc"
Output : 4
The longest subsequence is 4 because "abcd"
is a subsequence of first string, but not
a subsequence of second string.
Input : "abc", "abc"
Output : 0
Both strings are same, so there is no
uncommon subsequence.

Brute Force: In general, the first thought some people may have is to generate all possible 2n subsequences of both the strings and store their frequency in a hashmap. Longest subsequence whose frequency is equal to 1 will be the required subsequence. 

Implementation:


Output
8

Complexities:

  • Time complexity: O(2x + 2y), where x and y are the lengths of two strings.
  • Auxiliary Space : O(2x + 2y).

Efficient Algorithm:

If we analyze the problem carefully, it would seem much easier than it looks. All the three possible cases are as described below; 

  1. If both the strings are identical, for example: "ac" and "ac", it is obvious that no subsequence will be uncommon. Hence, return 0.
  2. If length(a) = length(b) and a ? b, for example: "abcdef" and "defghi", out of these two strings one string will never be a subsequence of other string. 
    Hence, return length(a) or length(b).
  3. If length(a) > length(b), for example: "abcdabcd" and "abcabc", in this case we can consider bigger string as a required subsequence because bigger string can not be a subsequence of smaller string. Hence, return max(length(a), length(b)).

Implementation:


Output
8

Complexity Analysis:

  • Time complexity: O(min(x, y)), where x and y are the lengths of two strings.
  • Auxiliary Space: O(1).

Approach#3: Using set()

Using set to compare the characters of the two strings. If the sets are equal, then there is no uncommon subsequence, and -1 is returned. Otherwise, the length of the longer string is returned.

Algorithm

1. Create a set of both strings.
2. Check if the sets are equal.
3. If they are equal, then return -1.
4. If they are not equal, then return the length of the longer string.


Output
8

Time Complexity: O(n) since it has to loop through the strings once to create the sets.

Auxiliary Space: O(n) since sets are used to store the characters of the strings.

Comment
Article Tags: