Given a string, check if a repeated subsequence is present in it or not. The repeated subsequence should have a length of 2 or more.

For example,

String XYBAXB has XB(XBXB) as a repeated subsequence
 
String XBXAXB has XX(XXX) as a repeated subsequence
 
String ABCA doesn’t have any repeated subsequence
 
String XYBYAXBY has XB(XBXB), XY(XYXY), YY(YYY), YB(YBYB), and YBY(YBYBY) as repeated subsequences.

Practice this problem

The idea is simple. If we discard all non-repeating elements from the string (having frequency of 1), and the resulting string is non-palindrome, then the string contains a repeated subsequence. If the resulting string is a palindrome and doesn’t have any character with frequency three or more, the string cannot have a repeated subsequence.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Repeated subsequence is present

Java


Download  Run Code

Output:

Repeated subsequence is present

Python


Download  Run Code

Output:

Repeated subsequence is present

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the length of the input string.

 
The problem can also be solved using dynamic programming. It is nothing but a variation of the Longest Common subsequence (LCS) problem. However, the time complexity of a dynamic programming solution is O(n2).