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.
Examples:
Input: S = “ab??”, K = 2
Output: abab
Input: S = “??????”, K = 3
Output: aaaaaa
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:
- If the size of the map is greater than 2, then print “-1” and break out of the loop.
- Otherwise, if the size of the map is 2, then replace each ‘?’ with that different character.
- Otherwise, replace all the ‘?’ with the character ‘a’.
- 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:
C++
#include "bits/stdc++.h"
using namespace std;
string modifyString(string& S, int K)
{
int N = S.length();
for ( int i = 0; i < K; i++) {
map< char , int > M;
for ( int j = i; j < N; j += K) {
M[S[j]]++;
}
if (M.size() > 2) {
return "-1" ;
}
else if (M.size() == 1) {
if (M[ '?' ] != 0) {
for ( int j = i; j < N; j += K) {
S[j] = 'a' ;
}
}
}
else if (M.size() == 2) {
char ch;
for ( auto & it : M) {
if (it.first != '?' ) {
ch = it.first;
}
}
for ( int j = i; j < N; j += K) {
S[j] = ch;
}
}
M.clear();
}
return S;
}
int main()
{
string S = "ab??" ;
int K = 2;
cout << modifyString(S, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static String modifyString( char [] S, int K)
{
int N = S.length;
for ( int i = 0 ; i < K; i++) {
HashMap<Character,Integer> M = new HashMap<>();
for ( int j = i; j < N; j += K) {
if (M.containsKey(S[j])){
M.put(S[j], M.get(S[j])+ 1 );
}
else {
M.put(S[j], 1 );
}
}
if (M.size() > 2 ) {
return "-1" ;
}
else if (M.size() == 1 ) {
if (M.get( '?' ) != 0 ) {
for ( int j = i; j < N; j += K) {
S[j] = 'a' ;
}
}
}
else if (M.size() == 2 ) {
char ch= ' ' ;
for (Map.Entry<Character,Integer> entry : M.entrySet()) {
if (entry.getKey() != '?' ) {
ch = entry.getKey();
}
}
for ( int j = i; j < N; j += K) {
S[j] = ch;
}
}
M.clear();
}
return String.valueOf(S);
}
public static void main(String[] args)
{
String S = "ab??" ;
int K = 2 ;
System.out.print(modifyString(S.toCharArray(), K));
}
}
|
Python3
def modifyString(S,K):
N = len (S)
S = list (S)
for i in range (K):
M = {}
for j in range (i,N,K):
if S[j] in M:
M[S[j]] + = 1
else :
M[S[j]] = 1
if ( len (M) > 2 ):
return "-1"
elif ( len (M) = = 1 ):
if (M[ '?' ] ! = 0 ):
for j in range (i,N,K):
S[j] = 'a'
elif ( len (M) = = 2 ):
ch = ''
for key,value in M.items():
if (key ! = '?' ):
ch = key
for j in range (i,N,K):
S[j] = ch
M.clear()
S = ''.join(S)
return S
if __name__ = = '__main__' :
S = "ab??"
K = 2
print (modifyString(S, K))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static String modifyString( char [] S, int K) {
int N = S.Length;
for ( int i = 0; i < K; i++) {
Dictionary< char , int > M = new Dictionary< char , int >();
for ( int j = i; j < N; j += K) {
if (M.ContainsKey(S[j])) {
M.Add(S[j], M[S[j]] + 1);
} else {
M.Add(S[j], 1);
}
}
if (M.Count > 2) {
return "-1" ;
} else if (M.Count == 1) {
if (M[ '?' ] != 0) {
for ( int j = i; j < N; j += K) {
S[j] = 'a' ;
}
}
}
else if (M.Count == 2) {
char ch = ' ' ;
foreach (KeyValuePair< char , int > entry in M) {
if (entry.Key != '?' ) {
ch = entry.Key;
}
}
for ( int j = i; j < N; j += K) {
S[j] = ch;
}
}
M.Clear();
}
return String.Join( "" ,S);
}
public static void Main(String[] args) {
String S = "ab??" ;
int K = 2;
Console.Write(modifyString(S.ToCharArray(), K));
}
}
|
Javascript
<script>
function modifyString(S, K)
{
let N = S.length;
for (let i = 0; i < K; i++)
{
let M = new Map();
for (let j = i; j < N; j += K)
{
if (M.has(S[j]))
{
M.set(M.get(S[j]),
M.get(S[j]) + 1);
}
else
{
M.set(S[j], 1);
}
}
if (M.size > 2)
{
return "-1" ;
}
else if (M.size == 1)
{
if (M.has( '?' ))
{
for (let j = i; j < N; j += K)
{
S = S.replace(S[j], 'a' );
}
}
}
else if (M.size == 2)
{
let ch;
for (let it of M.keys())
{
if (it != '?' )
{
ch = it;
}
}
for (let j = i; j < N; j += K)
{
S = S.replace(S[j], ch);
}
}
M.clear();
}
return S;
}
let S = "ab??" ;
let K = 2;
document.write(modifyString(S, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
17 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...