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.
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
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.
Below is the implementation of above idea.
Repeated Subsequence Exists
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 firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
- Number of subsequences of maximum length K containing no repeated elements
- Smallest length string with repeated replacement of two distinct adjacent
- Maximum Sum Subsequence of length k
- Subsequence X of length K such that gcd(X, X) + (X, X) + ... is maximized
- Maximum Bitwise AND value of subsequence of length K
- Length of Longest Balanced Subsequence
- Count subsequence of length three in a given string
- Maximum length subsequence possible of the form R^N K^N
- Length of longest common subsequence containing vowels
- Number of balanced bracket subsequence of length 2 and 4
- Length of the longest subsequence such that xor of adjacent elements is non-decreasing
- Length of Smallest Subsequence such that sum of elements is greater than equal to K
- Maximum length prefix of one string that occurs as subsequence in another
- Find the Increasing subsequence of length three with maximum product