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
- Length of longest subsequence whose XOR value is odd
- Subsequence X of length K such that gcd(X, X) + (X, X) + ... is maximized
- Length of Longest Balanced Subsequence
- Maximum Bitwise AND value of subsequence of length K
- Maximum length subsequence possible of the form R^N K^N
- Check if a subsequence of length K with odd sum exists
- Maximum bitwise OR value of subsequence of length K
- Count of K length subsequence whose product is even
- Count subsequence of length three in a given string
- Smallest Palindromic Subsequence of Even Length in Range [L, R]
- Check if an array has some palindromic subsequence of length at least 3
- Number of balanced bracket subsequence of length 2 and 4
- Length of Longest Prime Subsequence in an Array
- Length of longest common subsequence containing vowels
- Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray
- Length of longest subsequence of Fibonacci Numbers in an Array