Remove longest prefix of the String which has duplicate substring
Given a string S of length N, the task is to remove the longest prefix of the string which has at least one duplicate substring present in S.
Note: The duplicate substring cannot be the prefix itself
Input: S = “GeeksforGeeks”
Explanation: The longest substring which has a duplicate is “Geeks”.
After deleting this the remaining string becomes “forGeeks”.
Input: S = “aaaaa”
Explanation: Here the longest prefix which has a duplicate substring is “aaaa”.
So after deleting this the remaining string is “a”.
Note that the whole string is not selected because then the duplicate string is the prefix itself.
Approach: The problem can be solved based on the following idea:
Find all the characters which can be a starting point of a substring which is a duplicate of the prefix. Then from these points find the duplicate of the longest prefix and delete that prefix.
Follow the illustration below for a better understanding
For example take S = “aaaaa”
The possible starting points can be at indices 1, 2, 3, 4.
For index 1: The possible duplicate of the prefix is “aaaa”.
It has length = 4
For index 2: The possible duplicate of the prefix is “aaa”.
It has length = 3
For index 3: The possible duplicate of the prefix is “aa”.
It has length = 2
For index 4: The possible duplicate of the prefix is “a”.
It has length = 1
So remove the prefix of length 4. Therefore the string becomes “a”
Follow the approach mentioned below to solve the problem:
- Use two pointers: one to the start of the prefix (say i which is 0 initially) and the other (say j)to find the starting point of all possible duplicate substrings.
- Iterate j from 1 to N:
- If S[j] matches S[i] then use a pointer (say k) and iterate both i and k to find the length of the substring starting from j which is duplicate of the prefix.
- Update the maximum length.
- Set i again to 0.
- Delete the maximum length prefix.
Below is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(1)
Please Login to comment...