Longest Uncommon Subsequence

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 susequence of other string.
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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find longest uncommon
// subsequence using naive method
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
  
// function to calculate length of longest uncommon subsequence
int findLUSlength(string a, string b)
{
    /* creating an unordered map to map
       strings to their frequency*/
    unordered_map<string, int> map; 
    vector<string> strArr;
    strArr.push_back(a);
    strArr.push_back(b);
  
    // traversing all elements of vector strArr
    for (string s : strArr) 
    {
        /* Creating all possible subsequences, i.e 2^n*/
        for (int i = 0; i < (1 << s.length()); i++) 
        {
            string t = "";
            for (int j = 0; j < s.length(); j++) {
  
                /* ((i>>j) & 1) determines which  
                   character goes into string t*/
                if (((i >> j) & 1) != 0)  
                    t += s[j];
            }
  
            /* If common subsequence is found,
               increment its frequency*/
            if (map.count(t))
                map[t]++;
            else
                map[t] = 1;
        }
    }
    int res = 0;
    for (auto a : map) // traversing the map
    {
         // if frequency equals 1   
        if (a.second == 1)
            res = max(res, (int)a.first.length()); 
    }
    return res;
}
int main()
{
    // Your C++ Code
    string a = "abcdabcd", b = "abcabc"; // input strings
    cout << findLUSlength(a, b);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find longest uncommon
// subsequence using naive method
import java.io.*;
import java.util.*;
   
class GfG{
       
// function to calculate length of 
// longest uncommon subsequence
static int findLUSlength(String a, String b)
{
    // creating an unordered map to map
    // strings to their frequency
    HashMap<String, Integer> map= new HashMap<String, Integer>(); 
    Vector<String> strArr= new Vector<String>();
    strArr.add(a);
    strArr.add(b);
  
    // traversing all elements of vector strArr
    for (String s : strArr) 
    {
        // Creating all possible subsequences, i.e 2^n
        for (int i = 0; i < (1 << s.length()); i++) 
        {
            String t = "";
            for (int j = 0; j < s.length(); j++) {
  
                // ((i>>j) & 1) determines which 
                // character goes into string t
                if (((i >> j) & 1) != 0
                    t += s.charAt(j);
            }
  
            // If common subsequence is found,
            // increment its frequency
            if (map.containsKey(t))
                map.put(t,map.get(t)+1);
            else
                map.put(t,1);
        }
    }
    int res = 0;
    for (HashMap.Entry<String, Integer> entry : map.entrySet())
  
    // traversing the map
    {
        // if frequency equals 1 
        if (entry.getValue() == 1)
            res = Math.max(res, entry.getKey().length()); 
    }
    return res;
}
  
    // Driver code
    public static void main (String[] args) {
  
    // input strings
    String a = "abcdabcd", b = "abcabc"
       System.out.println(findLUSlength(a, b));
    }
}
  
// This code is contributed by Gitanjali.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find longest 
// uncommon subsequence using
// naive method
using System;
using System.Collections.Generic;
  
class GFG
{     
    // function to calculate 
    // length of longest
    // uncommon subsequence
    static int findLUSlength(string a, 
                             string b)
    {
        // creating an unordered 
        // map to map strings to
        // their frequency
        Dictionary<string, int> map = 
                   new Dictionary<string, int>(); 
        List<string> strArr =
                 new List<string>();
        strArr.Add(a);
        strArr.Add(b);
      
        // traversing all elements
        // of vector strArr
        foreach (string s in strArr)
        {
            // Creating all possible
            // subsequences, i.e 2^n
            for (int i = 0; 
                     i < (1 << s.Length); i++) 
            {
                string t = "";
                for (int j = 0; 
                         j < s.Length; j++) 
                {
      
                    // ((i>>j) & 1) determines 
                    // which character goes 
                    // into string t
                    if (((i >> j) & 1) != 0) 
                        t += s[j];
                }
      
                // If common subsequence 
                // is found, increment 
                // its frequency
                if (map.ContainsKey(t))
                {
                    int value = map[t] + 1;
                    map.Remove(t);
                    map.Add(t, value);
                }
                else
                    map.Add(t, 1);
            }
        }
        int res = 0;
        foreach (KeyValuePair<string, int
                             entry in map)
        // traversing the map
        {
            // if frequency equals 1 
            if (entry.Value == 1)
                res = Math.Max(res,
                           entry.Key.Length); 
        }
        return res;
    
      
    // Driver code
    static void Main () 
    
          
        // input strings
        string a = "abcdabcd",
               b = "abcabc"
          
        Console.Write(findLUSlength(a, b));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

chevron_right



Output:

8
  • 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)).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find longest uncommon 
// subsequence.
#include <iostream>
using namespace std;
  
// function to calculate length of longest
// uncommon subsequence
int findLUSlength(string a, string b)
{
    // Case 1: If strings are equal
    if (!a.compare(b)) 
        return 0;
  
     // for case 2 and case 3
    return max(a.length(), b.length());
}
  
// Driver code
int main()
{
    string a = "abcdabcd", b = "abcabc";
    cout << findLUSlength(a, b);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find longest uncommon
// subsequence using naive method
  
import java.io.*;
import java.util.*;
   
class GfG{
       
// function to calculate length of longest
// uncommon subsequence
static int findLUSlength(String a, String b)
{
    // Case 1: If strings are equal
    if (a.equals(b)==true
        return 0;
   
     // for case 2 and case 3
    return Math.max(a.length(), b.length());
}
    // Driver code
    public static void main (String[] args) {
  
    // input strings
    String a = "abcdabcd", b = "abcabc"
       System.out.println(findLUSlength(a, b));
    }
}
  
// This code is contributed by Gitanjali.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find
# longest uncommon
# subsequence using naive method
  
import math
  
# function to calculate
# length of longest
# uncommon subsequence
def findLUSlength( a, b):
  
    # Case 1: If strings are equal
    if (a==b) :
        return 0
   
     # for case 2 and case 3
    return max(len(a), len(b))
  
# Driver code
  
#input strings
a = "abcdabcd"
b = "abcabc" 
print (findLUSlength(a, b))
  
# This code is contributed by Gitanjali.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find longest uncommon
// subsequence using naive method.
using System;
  
class GfG {
      
    // function to calculate length
    // of longest uncommon subsequence
    static int findLUSlength(String a, String b)
    {
          
        // Case 1: If strings are equal
        if (a.Equals(b)==true
            return 0;
      
        // for case 2 and case 3
        return Math.Max(a.Length, b.Length);
    }
      
    // Driver code
    public static void Main ()
    {
  
        // input strings
        String a = "abcdabcd", b = "abcabc"
        Console.Write(findLUSlength(a, b));
    }
}
  
// This code is contributed by nitin mittal.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find longest 
// uncommon subsequence.
  
// function to calculate length 
// of longest uncommon subsequence
function findLUSlength($a, $b)
{
    // Case 1: If strings
    // are equal
    if (!strcmp($a, $b)) 
        return 0;
  
    // for case 2 
    // and case 3
    return max(strlen($a), 
               strlen($b));
}
  
// Driver code
$a = "abcdabcd"
$b = "abcabc";
echo (findLUSlength($a, $b));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

chevron_right



Output:

8

Complexity Analysis:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nitin mittal, manishshaw1



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.