![]() |
VOOZH | about |
Given a string, find if there is any subsequence of length 2 or more that repeats itself such that the two subsequences don’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 a 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 the same as the 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 the above idea.
Repeated Subsequence Exists
Time Complexity: O(n).
Auxiliary Space: O(256), because we are using frequency array size of MAX_CHAR.