Make S into an alternate binary string by replacing any character with 0 or 1 up to K times
Last Updated :
31 Jul, 2023
Given a string S and an integer K. You can choose any character from S and replace all occurrences of that character in S with either 0 or 1, up to K times, the task is to determine whether it is possible to create an alternating binary string from S after performing these replacements. If it is possible to create an alternating binary string, output the sequence of replacements made. Otherwise, output “NO”.
Note: An alternating binary string is a string consisting only of 0s and 1s such that no two adjacent characters are the same.
Examples:
Input: S = “akmzaxazmk”, K = 6
Output: YES, {a : 0, k : 1, m : 0, z : 1, x : 1}
Explanation:
- First operation: Replace all occurrences of ‘a’ with 0 then, S = 0kmz0x0zmk
- Second operation: Replace all occurrences of ‘k’ with 1 then, S = 01mz0x0zm1
- Third operation: Replace all occurrences of ‘m’ with 0 then, S = 010z0x0z01
- Fourth operation: Replace all occurrences of ‘z’ with 1 then, S = 01010x0101
- Fifth operation: Replace all occurrences of ‘x’ with 1 then, S = 0101010101
After 5 (Which are <=6) operations the string is converted into alternating binary string.
Input: S = “axnyyjk”, K= 1
Output: NO
Explanation: It can be verified that the S can’t be converted into alternating binary string using operation at most K times.
Approach: To solve the problem follow the below idea:
The problem can be solved using HashMap data structure. Let us divide the problem into three parts and know answer of each.
- Checking for validity, Whether conversion in alternating binary string is possible or not?
- Is it possible under at most K operations?
- Which character should be replace by 1 or 0?
- Validity: It must be noted that if all occurrences of a character occurs either at odd or even indices, Then that character is valid for replacing with either 0 or 1. This can be checked by calculating the difference between the indices of adjacent occurrences of same character. Formally, If two characters are same, Then the difference between their indices must be even(0 based indexing).
- For example: S = “axada”. character ‘a’ is placed at index 0, 2, and 4 respectively. The difference between adjacent occurrence is even. Formally, (2-0) and (4-2) is even.
- Number of operations required: As it is given that, We can use operation at most K times, Which means we can replace all occurrences of at most K distinct characters’ to either into 0 or 1. This can be check by size of the HashMap. If HashMap contains less than or equal to K distinct characters, Then conversion into alternating binary string is possible else not.
- Required character for replacement: Just traverse HashMap and replace the character with 0 if index corresponding to Character is even else replace the character with 1(Vice – versa is also possible).
Below are the steps for the above approach:
- Initialize a boolean variable flag and mark it initially true.
- Declare a HashMap let’s say map for storing indices.
- Traverse on the string,
- For each character in the input string, check if it has appeared before in the HashMap, and check if the difference between the indices of the current occurrence and the previous occurrence is even. If the difference is even, continue with the next iteration, otherwise, set the flag to false.
- If the current character is not present in the map then add it to the HashMap with its index value.
- Else mark the flag as false and break the loop.
- If the flag is true and map.size() is less than or equal to K, print YES else print NO.
- Traverse the map, if the character is at an even index then print 0 else 1 for the corresponding character.
Below is the code for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void AlterString(string s, int k){
bool flag= true ;
map< char , int >mp;
for ( int i=0;i<s.size();i++){
if (mp.find(s[i])!=mp.end()){
int end = mp[s[i]];
if ((end - i) % 2 == 0) {
continue ;
}
else {
flag = false ;
break ;
}
}
else {
mp[s[i]]=i;
}
}
if (flag and mp.size() <= k) {
cout<< "YES" <<endl;
auto it=mp.begin();
for (;it!=mp.end();it++){
cout<<it->first<< " : " <<((it->second)%2==0 ? 0 : 1)<<endl;
}
}
else {
cout<< "NO" ;
}
}
int main(){
string str = "akmzaxazmk" ;
int K = 6;
AlterString(str, K);
}
|
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
String str = "akmzaxazmk" ;
int K = 6 ;
AlterString(str, K);
}
static void AlterString(String str, int K)
{
boolean flag = true ;
HashMap<Character, Integer> map = new HashMap<>();
for ( int i = 0 ; i < str.length(); i++) {
if (map.containsKey(str.charAt(i))) {
int end = map.get(str.charAt(i));
if ((end - i) % 2 == 0 ) {
continue ;
}
else {
flag = false ;
break ;
}
}
else {
map.put(str.charAt(i), i);
}
}
if (flag && map.size() <= K) {
System.out.println( "YES" );
for (Map.Entry<Character, Integer> set :
map.entrySet()) {
System.out.println(
" " + set.getKey() + " : "
+ ((set.getValue() % 2 == 0 ) ? 0 : 1 ));
}
}
else {
System.out.println( "NO" );
}
}
}
|
Python3
def AlterString(input_str, K):
flag = True
map = {}
for i in range ( len (input_str)):
if input_str[i] in map :
end = map [input_str[i]]
if (end - i) % 2 = = 0 :
continue
else :
flag = False
break
else :
map [input_str[i]] = i
if flag and len ( map ) < = K:
print ( "YES" )
for key, value in map .items():
print ( " " + key + " : " + str ((value % 2 = = 0 ) and 0 or 1 ))
else :
print ( "NO" )
if __name__ = = '__main__' :
input_str = "akmzaxazmk"
K = 6
AlterString(input_str, K)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void Main( string [] args) {
string str = "akmzaxazmk" ;
int K = 6;
AlterString(str, K);
}
static void AlterString( string str, int K) {
bool flag = true ;
Dictionary< char , int > map = new Dictionary< char , int >();
for ( int i = 0; i < str.Length; i++) {
if (map.ContainsKey(str[i])) {
int end = map[str[i]];
if ((end - i) % 2 == 0) {
continue ;
}
else {
flag = false ;
break ;
}
}
else {
map.Add(str[i], i);
}
}
if (flag && map.Count <= K) {
Console.WriteLine( "YES" );
foreach (KeyValuePair< char , int > set in map) {
Console.WriteLine( " " + set .Key + " : " + (( set .Value % 2 == 0) ? 0 : 1));
}
}
else {
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function alterString(input_str, K) {
let flag = true ;
let map = {};
for (let i = 0; i < input_str.length; i++) {
if (input_str[i] in map) {
let end = map[input_str[i]];
if ((end - i) % 2 === 0) {
continue ;
}
else {
flag = false ;
break ;
}
}
else {
map[input_str[i]] = i;
}
}
if (flag && Object.keys(map).length <= K) {
console.log( "YES" );
for (let [key, value] of Object.entries(map)) {
console.log( " " + key + " : " + ((value % 2 === 0) ? 0 : 1));
}
} else {
console.log( "NO" );
}
}
let input_str = "akmzaxazmk" ;
let K = 6;
alterString(input_str, K);
|
Output
YES
a : 0
k : 1
m : 0
x : 1
z : 1
Time Complexity: O(N)
Auxiliary Space: O(26) = ~O(1), As HashMap is used for storing indices. There can be at most 26 different alphabets in S.
Share your thoughts in the comments
Please Login to comment...