Repeated subsequence of length 2 or more

01 Jul, 2022
Given a string, find if there is any subsequence of length 2 or more that repeats itself such that the two subsequences doesn’t have the same character at the same position, i.e., any 0’th or 1st character in the two subsequences shouldn’t have the same index in the original string.
Example: 
Input: ABCABD
Output: Repeated Subsequence Exists (A B is repeated) 

Input: ABBB
Output: Repeated Subsequence Exists (B B is repeated)

Input: AAB
Output: Repeated Subsequence Doesn't Exist (Note that 
A B cannot be considered as repeating because B is at
same position in two subsequences).

Input: AABBC
Output: Repeated Subsequence Exists (A B is repeated)

Input: ABCDACB
Output: Repeated Subsequence Exists (A B is repeated)

Input: ABCD
Output: Repeated Subsequence Doesn't Exist
The problem is classic variation of longest common subsequence problem. We have discussed Dynamic programming solution here. Dynamic programming solution takes O(n2) time and space. 
In this post, O(n) time and space approach is discussed.
The idea is to remove all the non-repeated characters from the string and check if the resultant string is palindrome or not. If the remaining string is palindrome then it is not repeated, else there is a repetition. One special case we need to handle for inputs like “AAA”, which are palindrome but their repeated subsequence exists. Repeated subsequence exists for a palindrome string if it is of odd length and its middle letter is same as left(or right) character.
Algorithm: 
Step 1: Initialize the input string.
Step 2: Find the length of input string
Step 3: Create an array and store all characters and their frequencies in it.
Step 4: Traverse the input string and store the frequency of all characters in another array.
Step 5: increment the count if the letters are repeating, if count is more than two return true.
Step 6: In place of non repeating characters put ‘\0’ .
Step 7: check if the string is palindrome, if it’s palindrome return false else true.
Step 7: Print the output.
Below is the implementation of above idea. 
C++
Java
Python3
C#
Javascript
// C++ program to check if any repeated// subsequence exists in the string#include <bits/stdc++.h>#define MAX_CHAR 256using namespace std; // A function to check if a string str is palindromebool isPalindrome(char str[], int l, int h){    // l and h are leftmost and rightmost corners of str    // Keep comparing characters while they are same    while (h > l)        if (str[l++] != str[h--])            return false;     return true;} // The main function that checks if repeated// subsequence exists in the stringint check(char str[]){    // Find length of input string    int n = strlen(str);     // Create an array to store all characters and their    // frequencies in str[]    int freq[MAX_CHAR] = { 0 };     // Traverse the input string and store frequencies    // of all characters in freq[] array.    for (int i = 0; i < n; i++)    {        freq[str[i]]++;         // If the character count is more than 2        // we found a repetition        if (freq[str[i]] > 2)            return true;    }     // In-place remove non-repeating characters    // from the string    int k = 0;    for (int i = 0; i < n; i++)        if (freq[str[i]] > 1)            str[k++] = str[i];    str[k] = '\0';     // check if the resultant string is palindrome    if (isPalindrome(str, 0, k-1))    {        // special case - if length is odd        // return true if the middle character is        // same as previous one        if (k & 1)            return str[k/2] == str[k/2 - 1];         // return false if string is a palindrome        return false;    }     // return true if string is not a palindrome    return true;} // Driver codeint main(){    char str[] = "ABCABD";     if (check(str))        cout << "Repeated Subsequence Exists";    else        cout << "Repeated Subsequence Doesn't Exists";     return 0;}
// Java program to check if any repeated// subsequence exists in the stringclass GFG{    static int MAX_CHAR = 256;     // A function to check    // if a string str is palindrome    public static boolean isPalindrome(String str,                                       int l, int h)    {                 // l and h are leftmost and rightmost corners of str        // Keep comparing characters while they are same        while(h > l)            if (str.charAt(l++) != str.charAt(h--))                return false;                 return true;    }     // The main function that checks if repeated    // subsequence exists in the string    public static boolean check(String str)    {                 // Find length of input string        int n = str.length();             // Create an array to store all characters        // and their frequencies in str[]        int[] freq = new int[MAX_CHAR];             // Traverse the input string and store frequencies        // of all characters in freq[] array.        for (int i = 0; i < n; i++)        {            freq[str.charAt(i)]++;                 // If the character count is more than 2            // we found a repetition            if (freq[str.charAt(i)] > 2)                return true;        }             // In-place remove non-repeating characters        // from the string        int k = 0;        for (int i = 0; i < n; i++)            if (freq[str.charAt(i)] > 1)                str.replace(str.charAt(k++),                            str.charAt(i));        str.replace(str.charAt(k), '\0');         // check if the resultant string is palindrome        if (isPalindrome(str, 0, k - 1))        {             // special case - if length is odd            // return true if the middle character is            // same as previous one            if ((k & 1) == 1)            {                 // It is checked so that                // StringIndexOutOfBounds can be avoided                if (k / 2 >= 1)                    return (str.charAt(k / 2) ==                            str.charAt(k / 2 - 1));            }                 // return false if string is a palindrome            return false;        }             // return true if string is not a palindrome        return true;    }         // Driver Code    public static void main(String[] args)    {        String str = "ABCABD";                 if (check(str))            System.out.println("Repeated Subsequence Exists");        else            System.out.println("Repeated Subsequence" +                               " Doesn't Exists");    }} // This code is contributed by sanjeev2552
# Python3 program to check if any repeated# subsequence exists in the StringMAX_CHAR = 256 # A function to check# if a String Str is palindromedef isPalindrome(Str, l, h):         # l and h are leftmost and rightmost corners of Str    # Keep comparing characters while they are same    while (h > l):        if (Str[l] != Str[h]):            l += 1            h -= 1            return False     return True # The main function that checks if repeated# subsequence exists in the Stringdef check(Str):         # Find length of input String    n = len(Str)     # Create an array to store all characters    # and their frequencies in Str[]    freq = [0 for i in range(MAX_CHAR)]     # Traverse the input String and    # store frequencies of all characters    # in freq[] array.    for i in range(n):         freq[ord(Str[i])] += 1         # If the character count is more than 2        # we found a repetition        if (freq[ord(Str[i])] > 2):            return True     # In-place remove non-repeating characters    # from the String    k = 0    for i in range(n):        if (freq[ord(Str[i])] > 1):            Str[k] = Str[i]            k += 1    Str[k] = '\0'     # check if the resultant String is palindrome    if (isPalindrome(Str, 0, k - 1)):                 # special case - if length is odd        # return true if the middle character is        # same as previous one        if (k & 1):            return Str[k // 2] == Str[k // 2 - 1]         # return false if String is a palindrome        return False     # return true if String is not a palindrome    return True # Driver codeS = "ABCABD"Str = [i for i in S] if (check(Str)):    print("Repeated Subsequence Exists")else:    print("Repeated Subsequence Doesn't Exists") # This code is contributed by Mohit Kumar
// C# program to check if any repeated// subsequence exists in the stringusing System;     class GFG{    static int MAX_CHAR = 256;     // A function to check    // if a string str is palindrome    public static Boolean isPalindrome(String str,                                    int l, int h)    {                 // l and h are leftmost and rightmost corners of str        // Keep comparing characters while they are same        while(h > l)            if (str[l++] != str[h--])                return false;                 return true;    }     // The main function that checks if repeated    // subsequence exists in the string    public static Boolean check(String str)    {                 // Find length of input string        int n = str.Length;             // Create an array to store all characters        // and their frequencies in str[]        int[] freq = new int[MAX_CHAR];             // Traverse the input string and store frequencies        // of all characters in freq[] array.        for (int i = 0; i < n; i++)        {            freq[str[i]]++;                 // If the character count is more than 2            // we found a repetition            if (freq[str[i]] > 2)                return true;        }             // In-place remove non-repeating characters        // from the string        int k = 0;        for (int i = 0; i < n; i++)            if (freq[str[i]] > 1)                str.Replace(str[k++],                            str[i]);        str.Replace(str[k], '\0');         // check if the resultant string is palindrome        if (isPalindrome(str, 0, k - 1))        {             // special case - if length is odd            // return true if the middle character is            // same as previous one            if ((k & 1) == 1)            {                 // It is checked so that                // StringIndexOutOfBounds can be avoided                if (k / 2 >= 1)                    return (str[k / 2] ==                            str[k / 2 - 1]);            }                 // return false if string is a palindrome            return false;        }             // return true if string is not a palindrome        return true;    }         // Driver Code    public static void Main(String[] args)    {        String str = "ABCABD";                 if (check(str))            Console.WriteLine("Repeated Subsequence Exists");        else            Console.WriteLine("Repeated Subsequence" +                            " Doesn't Exists");    }} // This code is contributed by Princi Singh
<script>// Javascript program to check if any repeated// subsequence exists in the string         let MAX_CHAR = 256;         // A function to check    // if a string str is palindrome    function isPalindrome(str,l,h)    {        // l and h are leftmost and rightmost corners of str        // Keep comparing characters while they are same        while(h > l)            if (str[l++] != str[h--])                return false;                   return true;    }         // The main function that checks if repeated    // subsequence exists in the string    function check(str)    {        // Find length of input string        let n = str.length;               // Create an array to store all characters        // and their frequencies in str[]        let freq = new Array(MAX_CHAR);        for(let i=0;i<freq.length;i++)        {            freq[i]=0;        }               // Traverse the input string and store frequencies        // of all characters in freq[] array.        for (let i = 0; i < n; i++)        {            freq[str[i].charCodeAt(0)]++;                   // If the character count is more than 2            // we found a repetition            if (freq[str[i].charCodeAt(0)] > 2)                return true;        }               // In-place remove non-repeating characters        // from the string        let k = 0;        for (let i = 0; i < n; i++)            if (freq[str[i].charCodeAt(0)] > 1)                str.replace(str[k++],                            str[i]);        str.replace(str[k], '\0');           // check if the resultant string is palindrome        if (isPalindrome(str, 0, k - 1))        {               // special case - if length is odd            // return true if the middle character is            // same as previous one            if ((k & 1) == 1)            {                   // It is checked so that                // StringIndexOutOfBounds can be avoided                if (k / 2 >= 1)                    return (str[Math.floor(k/2)] ==                            str[Math.floor(k/2) -1]);            }                   // return false if string is a palindrome            return false;        }               // return true if string is not a palindrome        return true;    }         // Driver Code    let str = "ABCABD";    if (check(str))        document.write("Repeated Subsequence Exists");    else        document.write("Repeated Subsequence" +                               " Doesn't Exists");         // This code is contributed by unknown2108</script>
Repeated Subsequence Exists
Time Complexity: O(n).
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
ShubhamRathi1
mohit kumar 29
sanjeev2552
princi singh
unknown2108
varshagumber28
kanheremahesh1729
hardikkoriintern
subsequence
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications