# Repeated subsequence of length 2 or more

• Difficulty Level : Hard
• Last Updated : 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++

 `// C++ program to check if any repeated` `// subsequence exists in the string` `#include ` `#define MAX_CHAR 256` `using` `namespace` `std;`   `// A function to check if a string str is palindrome` `bool` `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 string` `int` `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 code` `int` `main()` `{` `    ``char` `str[] = ``"ABCABD"``;`   `    ``if` `(check(str))` `        ``cout << ``"Repeated Subsequence Exists"``;` `    ``else` `        ``cout << ``"Repeated Subsequence Doesn't Exists"``;`   `    ``return` `0;` `}`

## Java

 `// Java program to check if any repeated ` `// subsequence exists in the string` `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.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

 `# Python3 program to check if any repeated` `# subsequence exists in the String` `MAX_CHAR ``=` `256`   `# A function to check ` `# if a String Str is palindrome` `def` `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 String` `def` `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 code` `S ``=` `"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#

 `// C# program to check if any repeated ` `// subsequence exists in the string` `using` `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`

## Javascript

 ``

Output

`Repeated Subsequence Exists`

Time Complexity: O(n).