Given a string S of small letter English alphabet. The task is to find how many unique non-empty substrings of S are present in an infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”.Note : The infinite wraparound string will look like this: “…efghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.
Examples :
Input : S = "cac" Output : 2 Explanation : The two substrings of string S are "a" and "c" which are present in the infinite wraparound string. Input : S = "zab" Output : 6 Explanation : The six substrings of S are "z", "a", "b", "za", "ab", "zab" which are present in infinite wraparound string.
Naive Approach :
Run two loops and check for each substring of S, if it is a substring of the infinite wraparound string then insert it into hashmap. Finally, return the size of hashmap.
Time Complexity : O(N2)
Efficient Approach :
We will use a dynamic programming approach to solve this problem. The idea is if we know the maximum length of a unique substring in S ending with the letter ‘X’ then, the count of all unique substring ends with ‘X’ equals to the length of the contiguous substring ends with that letter. So for a substring “abcd”, the maximum number of unique substring ends with ‘d’ is 4, apparently, they are “abcd”, “bcd”, “cd” and “d”. Also, If there are overlapping substrings, we only need to consider the longest one because it covers all the possible substrings.
Implementation :
// C++ program to find all unique substring
// present in infinite wraparound string
#include <bits/stdc++.h>
using namespace std;
// function to find all unique substring
// present in infinite wraparound string
int findSubstringInWraproundString(string &S,int N) {
// auilary array to store maximum length
// of unique substring for each character
// present in S
int freq[26];
memset(freq, 0, sizeof freq);
for(int i = 0; i < N; ++i)
{
// Initialize freq array with current letter
freq[S[i]-'a'] = max(freq[S[i]-'a'], 1);
// get current letter position in alphabet
int pos = S[i] - 'a';
int j = i + 1;
while(j < N && (S[j] - 'a') == (pos + 1) % 26)
{
// update frequency array for each character
freq[S[j]-'a']=max(freq[S[j]-'a'],j-i+1);
// update to next character position
pos++;
j++;
}
// update i with new postion
i = j - 1;
}
// return sum of maximum length of all possible
// substring ending with each characters.
return accumulate(begin(freq), end(freq), 0);
}
// Driver code
int main() {
string S = "zab";
int N = S.length();
// function to find required answer
cout<<findSubstringInWraproundString(S, N);
return 0;
}
Output : 6
Time Complexity : O(N)