Modify string by inserting characters such that every K-length substring consists of unique characters only
Given string S of size N consisting of K distinct characters and (N – K) ‘?’s, the task is to replace all ‘?’ with existing characters from the string such that every substring of size K has consisted of unique characters only. If it is not possible to do so, then print “-1”.
Input: S = “????abcd”, K = 4
Replacing the 4 ‘?’s with “abcd” modifies string S to “abcdabcd”, which satisfies the given condition.
Input: S = “?a?b?c”, K = 3
Replacing S with ‘b’, S with ‘c’ and S with ‘a’ modifies string S to “bacbac”, which satisfies the given condition.
Approach: The idea is based on the observation that in the final resultant string, each character must appear after exactly K places, like the (K + 1)th character must be the same as 1st, (K + 2)th character must be the same as 2nd, and so on.
Follow the steps below to solve the problem:
- Initialize a hashmap M to store the positions of characters.
- Traverse the string S using the variable i and if the current character S[i] is not the same as ‘?‘, then update M[i % K] = S[i].
- Traverse the string S using the variable i and if the value of i%k is not present in map M, then print “-1” and break out of the loop. Else update S[i] to M[i % K].
- After the above steps, if the loop doesn’t break, then print S as the resultant string.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)