Lexicographically smallest string with period K possible by replacing ‘?’s from a given string
Given a string S consisting of N lowercase characters and character ‘?’ and a positive integer K, the task is to replace each character ‘?’ with some lowercase alphabets such that the given string becomes a period of K. If it is not possible to do so, then print “-1”.
A string is said to be a period of K if and only if the length of the string is a multiple of K and for all possible value of i over the range [0, K) the value S[i + K], S[i + 2*K], S[i + 3*K], …, remains the same.
Input: S = “ab??”, K = 2
Input: S = “??????”, K = 3
Naive Approach: The given approach can also be solved by generating all possible combination of strings by replacing each character ‘?’ with any lowercase characters and print that string that have each substring of size K is the same.
Time Complexity: O(26M), where M is the number of ‘?’ in the string S.
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by traversing the string in a way such that the first, second, third, and so on characters are traversed and if all the characters are ‘?’ then replace it with character ‘a’, Otherwise, if there exists only one distinct character at each respective position then replace ‘?’ with that character, Otherwise, the string can’t be modified as per the given criteria and hence, print “-1”. Follow the steps below to solve the problem:
- Iterate a loop over the range [0, K] using the variable i and perform the following steps:
- Initialize a map, say M to store the frequency of characters of substring at positions i.
- Traverse the given string over the range [i, N] using the variable j with an increment of K and store the frequency of the character S[j] by 1 in the map M.
- After completing the above steps perform the following:
- After completing the above steps, if the string can be modified, then print the string S as the result string.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.