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 email@example.com. 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
- Smallest length string with repeated replacement of two distinct adjacent
- Subsequence X of length K such that gcd(X, X) + (X, X) + ... is maximized
- Maximum Sum Subsequence of length k
- Length of Longest Balanced Subsequence
- Maximum length subsequence possible of the form R^N K^N
- Count subsequence of length three in a given string
- Maximum Bitwise AND value of subsequence of length K
- Length of longest common subsequence containing vowels
- Number of balanced bracket subsequence of length 2 and 4
- Maximum length prefix of one string that occurs as subsequence in another
- Find the Increasing subsequence of length three with maximum product
- Find length of longest subsequence of one string which is substring of another string
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Second most repeated word in a sequence