Given stringS 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 Output: abcdabcd Explanation: Replacing the 4 ‘?’s with “abcd” modifies string S to “abcdabcd”, which satisfies the given condition.
Input: S = “?a?b?c”, K = 3 Output: bacbac Explanation: 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 hashmapM to store the positions of characters.
Traverse the stringS using the variable i and if the current character S[i] is not the same as ‘?‘, then update M[i % K] = S[i].
Please Login to comment...