Lexicographically smallest string with period K possible by replacing '?'s from a given string
Last Updated :
17 Apr, 2023
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++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
// Function to modify the given string
// such that string S is a period of K
string modifyString(string& S, int K)
{
int N = S.length();
// Iterate over the range [0, K]
for (int i = 0; i < K; i++) {
// Stores the frequency of the
// characters S[i + j*K]
map<char, int> M;
// Iterate over the string with
// increment of K
for (int j = i; j < N; j += K) {
M[S[j]]++;
}
// Print "-1"
if (M.size() > 2) {
return "-1";
}
else if (M.size() == 1) {
if (M['?'] != 0) {
// Replace all characters
// of the string with '?'
// to 'a' to make it smallest
for (int j = i; j < N; j += K) {
S[j] = 'a';
}
}
}
// Otherwise
else if (M.size() == 2) {
char ch;
// Find the character other
// than '?'
for (auto& it : M) {
if (it.first != '?') {
ch = it.first;
}
}
// Replace all characters
// of the string with '?'
// to character ch
for (int j = i; j < N; j += K) {
S[j] = ch;
}
}
// Clear the map M
M.clear();
}
// Return the modified string
return S;
}
// Driver Code
int main()
{
string S = "ab??";
int K = 2;
cout << modifyString(S, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to modify the given String
// such that String S is a period of K
static String modifyString(char[] S, int K)
{
int N = S.length;
// Iterate over the range [0, K]
for (int i = 0; i < K; i++) {
// Stores the frequency of the
// characters S[i + j*K]
HashMap<Character,Integer> M = new HashMap<>();
// Iterate over the String with
// increment of K
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);
}
}
// Print "-1"
if (M.size() > 2) {
return "-1";
}
else if (M.size() == 1) {
if (M.get('?') != 0) {
// Replace all characters
// of the String with '?'
// to 'a' to make it smallest
for (int j = i; j < N; j += K) {
S[j] = 'a';
}
}
}
// Otherwise
else if (M.size() == 2) {
char ch=' ';
// Find the character other
// than '?'
for (Map.Entry<Character,Integer> entry : M.entrySet()) {
if (entry.getKey() != '?') {
ch = entry.getKey();
}
}
// Replace all characters
// of the String with '?'
// to character ch
for (int j = i; j < N; j += K) {
S[j] = ch;
}
}
// Clear the map M
M.clear();
}
// Return the modified String
return String.valueOf(S);
}
// Driver Code
public static void main(String[] args)
{
String S = "ab??";
int K = 2;
System.out.print(modifyString(S.toCharArray(), K));
}
}
// This code is contributed by umadevi9616
Python3
# python 3 program for the above approach
# Function to modify the given string
# such that string S is a period of K
def modifyString(S,K):
N = len(S)
S = list(S)
# Iterate over the range [0, K]
for i in range(K):
# Stores the frequency of the
# characters S[i + j*K]
M = {}
# Iterate over the string with
# increment of K
for j in range(i,N,K):
if S[j] in M:
M[S[j]] += 1
else:
M[S[j]] = 1
# Print "-1"
if (len(M) > 2):
return "-1"
elif (len(M) == 1):
if (M['?'] != 0):
# Replace all characters
# of the string with '?'
# to 'a' to make it smallest
for j in range(i,N,K):
S[j] = 'a'
# Otherwise
elif(len(M) == 2):
ch = ''
# Find the character other
# than '?'
for key,value in M.items():
if (key != '?'):
ch = key
# Replace all characters
# of the string with '?'
# to character ch
for j in range(i,N,K):
S[j] = ch
# Clear the map M
M.clear()
S = ''.join(S)
# Return the modified string
return S
# Driver Code
if __name__ == '__main__':
S = "ab??"
K = 2
print(modifyString(S, K))
# This code is contributed by ipg2016107.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG {
// Function to modify the given String
// such that String S is a period of K
static String modifyString(char[] S, int K) {
int N = S.Length;
// Iterate over the range [0, K]
for (int i = 0; i < K; i++) {
// Stores the frequency of the
// characters S[i + j*K]
Dictionary<char, int> M = new Dictionary<char, int>();
// Iterate over the String with
// increment of K
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);
}
}
// Print "-1"
if (M.Count > 2) {
return "-1";
} else if (M.Count == 1) {
if (M['?'] != 0) {
// Replace all characters
// of the String with '?'
// to 'a' to make it smallest
for (int j = i; j < N; j += K) {
S[j] = 'a';
}
}
}
// Otherwise
else if (M.Count == 2) {
char ch = ' ';
// Find the character other
// than '?'
foreach (KeyValuePair<char, int> entry in M) {
if (entry.Key != '?') {
ch = entry.Key;
}
}
// Replace all characters
// of the String with '?'
// to character ch
for (int j = i; j < N; j += K) {
S[j] = ch;
}
}
// Clear the map M
M.Clear();
}
// Return the modified String
return String.Join("",S);
}
// Driver Code
public static void Main(String[] args) {
String S = "ab??";
int K = 2;
Console.Write(modifyString(S.ToCharArray(), K));
}
}
// This code is contributed by umadevi9616
JavaScript
<script>
// JavaScript program for the above approach
// Function to modify the given string
// such that string S is a period of K
function modifyString(S, K)
{
let N = S.length;
// Iterate over the range [0, K]
for(let i = 0; i < K; i++)
{
// Stores the frequency of the
// characters S[i + j*K]
let M = new Map();
// Iterate over the string with
// increment of K
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);
}
}
// Print "-1"
if (M.size > 2)
{
return "-1";
}
else if (M.size == 1)
{
if (M.has('?'))
{
// Replace all characters
// of the string with '?'
// to 'a' to make it smallest
for(let j = i; j < N; j += K)
{
S = S.replace(S[j], 'a');
}
}
}
// Otherwise
else if (M.size == 2)
{
let ch;
// Find the character other
// than '?'
for(let it of M.keys())
{
if (it != '?')
{
ch = it;
}
}
// Replace all characters
// of the string with '?'
// to character ch
for(let j = i; j < N; j += K)
{
S = S.replace(S[j], ch);
}
}
// Clear the map M
M.clear();
}
// Return the modified string
return S;
}
// Driver Code
let S = "ab??";
let K = 2;
document.write(modifyString(S, K));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read