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++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Method for checking the string is
// valid or not For converting into
// an alternating string
void AlterString(string s,int k){
// Boolean Flag is used
// for storing validity of s
bool flag=true;
// HashMap declared for
// storing indices
map<char,int>mp;
// Loop for traversing on string
for(int i=0;i<s.size();i++){
// If map contains the current
// character of Loop then
// checking the difference of
// indices with previous
// occurence
if(mp.find(s[i])!=mp.end()){
int end = mp[s[i]];
if ((end - i) % 2 == 0) {
continue;
}
else {
flag = false;
break;
}
}
// If map doesn't contains the
// current element then
// initializing key and value
// with character and index
// value respectively.
else{
mp[s[i]]=i;
}
}
// Cheking that if it is possible
// under at most K number of
// operations
if (flag and mp.size() <= k) {
cout<<"YES"<<endl;
// for (Map.Entry<Character, Integer> set :
// map.entrySet()) {
// System.out.println(
// " " + set.getKey() + " : "
// + ((set.getValue() % 2 == 0) ? 0 : 1));
// }
auto it=mp.begin();
for(;it!=mp.end();it++){
cout<<it->first<<" : "<<((it->second)%2==0 ? 0 : 1)<<endl;
}
}
else {
cout<<"NO";
}
}
int main(){
// Input String
string str = "akmzaxazmk";
int K = 6;
// Function call
AlterString(str, K);
}
Java
// Java code to implement the approach
import java.util.*;
public class GFG {
// Driver function
public static void main(String[] args)
{
// Input String
String str = "akmzaxazmk";
int K = 6;
// Function call
AlterString(str, K);
}
// Method for checking the string is
// valid or not For converting into
// an alternating string
static void AlterString(String str, int K)
{
// Boolean Flag is used
// for storing validity of S
boolean flag = true;
// HashMap declared for
// storing indices
HashMap<Character, Integer> map = new HashMap<>();
// Loop for traversing on string
for (int i = 0; i < str.length(); i++) {
// If map contains the current
// character of Loop then
// checking the difference of
// indices with previous
// occurence
if (map.containsKey(str.charAt(i))) {
int end = map.get(str.charAt(i));
if ((end - i) % 2 == 0) {
continue;
}
else {
flag = false;
break;
}
}
// If map doesn't contains the
// current element then
// initializing key and value
// with character and index
// value respectively.
else {
map.put(str.charAt(i), i);
}
}
// Cheking that if it is possible
// under at most K number of
// operations
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
# Function for checking the string is valid
# or not for converting into an alternating string
def AlterString(input_str, K):
# Boolean Flag is used
# for storing validity of S
flag = True
# Dictionary declared for
# storing indices
map = {}
# Loop for traversing on string
for i in range(len(input_str)):
# If dictionary contains the current
# character of Loop then
# checking the difference of
# indices with previous
# occurrence
if input_str[i] in map:
end = map[input_str[i]]
if (end - i) % 2 == 0:
continue
else:
flag = False
break
# If dictionary doesn't contain the
# current element then
# initializing key and value
# with character and index
# value respectively.
else:
map[input_str[i]] = i
# Checking if it is possible to convert the
# string into an alternating string under
# at most K number of operations
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")
# Driver function
if __name__ == '__main__':
# Input String
input_str = "akmzaxazmk"
K = 6
# Function call
AlterString(input_str, K)
C#
using System;
using System.Collections.Generic;
class GFG {
// Driver function
static void Main(string[] args) {
// Input String
string str = "akmzaxazmk";
int K = 6;
// Function call
AlterString(str, K);
}
// Method for checking the string is
// valid or not For converting into
// an alternating string
static void AlterString(string str, int K) {
// Boolean Flag is used
// for storing validity of S
bool flag = true;
// Dictionary declared for
// storing indices
Dictionary<char, int> map = new Dictionary<char, int>();
// Loop for traversing on string
for (int i = 0; i < str.Length; i++) {
// If map contains the current
// character of Loop then
// checking the difference of
// indices with previous
// occurence
if (map.ContainsKey(str[i])) {
int end = map[str[i]];
if ((end - i) % 2 == 0) {
continue;
}
else {
flag = false;
break;
}
}
// If map doesn't contains the
// current element then
// initializing key and value
// with character and index
// value respectively.
else {
map.Add(str[i], i);
}
}
// Cheking that if it is possible
// under at most K number of
// operations
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
// Method for checking the string is
// valid or not For converting into
// an alternating string
function alterString(input_str, K) {
// Boolean Flag is used
// for storing validity of s
let flag = true;
// HashMap declared for
// storing indices
let map = {};
// Loop for traversing on string
for (let i = 0; i < input_str.length; i++) {
// If map contains the current
// character of Loop then
// checking the difference of
// indices with previous
// occurence
if (input_str[i] in map) {
let end = map[input_str[i]];
if ((end - i) % 2 === 0) {
continue;
}
else {
flag = false;
break;
}
}
// If map doesn't contains the
// current element then
// initializing key and value
// with character and index
// value respectively.
else {
map[input_str[i]] = i;
}
}
// Cheking that if it is possible
// under at most K number of
// operations
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");
}
}
// Test case
let input_str = "akmzaxazmk";
let K = 6;
alterString(input_str, K);
OutputYES
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.
Similar Reads
Make Palindrome binary string with exactly a 0s and b 1s by replacing wild card ?
Given a string S of N characters consisting of '?', '0', and '1' and two integers a and b, the task is to find a palindromic binary string with exactly a 0s and b 1s by replacing the '?' with either '0' or '1'. Examples: Input: S = "10?????1", a = 4, b = 4Output: 10100101Explanation: The output stri
12 min read
Check if it is possible to rearrange a binary string with alternate 0s and 1s
Given a binary string of length, at least two. We need to check if it is possible to rearrange a binary string such that there are alternate 0s and 1s. If possible, then the output is YES, otherwise the output is NO. Examples: Input : 1011 Output : NO We can't rearrange the string such that it has a
5 min read
Replace '?' to convert given string to a binary string with maximum count of '0' and "10"
Given string str, consisting of three different types of characters '0', '1' and '?', the task is to convert the given string to a binary string by replacing the '?' characters with either '0' or '1' such that the count of 0s and 10 in the binary string is maximum. Examples: Input: str = 10?0?11Outp
4 min read
Make given Binary Strings equal by replacing two consecutive 0s with single 1 repeatedly
Given two binary strings str1 and str2, the task is to check whether it is possible to convert str1 to str2 by combining two consecutive 0's into a single 1 repeatedly. Examples: Input: str1 = "00100", str2 = "111" Output: Yes Explanation: Combine first two zeros to one and combine last two zeros to
6 min read
Minimum number of replacements to make the binary string alternating | Set 2
Given a binary string str, the task is to find the minimum number of characters in the string that have to be replaced in order to make the string alternating (i.e. of the form 01010101... or 10101010...).Examples: Input: str = "1100" Output: 2 Replace 2nd character with '0' and 3rd character with '
5 min read
Minimum number of characters to be removed to make a binary string alternate
Given a binary string, the task is to find minimum number of characters to be removed from it so that it becomes alternate. A binary string is alternate if there are no two consecutive 0s or 1s.Examples : Input : s = "000111" Output : 4 We need to delete two 0s and two 1s to make string alternate. I
4 min read
Count of possible distinct Binary strings after replacing "11" with "0"
Given a binary string str of size N containing 0 and 1 only, the task is to count all possible distinct binary strings when a substring "11" can be replaced by "0". Examples: Input: str = "11011"Output: 4Explanation: All possible combinations are "11011", "0011", "1100", "000". Input: str = "1100111
15 min read
Count Substrings that can be made of length 1 by replacing "01" or "10" with 1 or 0
Given a binary string S of length N, the task is to find the number of pairs of integers [L, R] 1 ⤠L < R ⤠N such that S[L . . . R] (the substring of S from L to R) can be reduced to 1 length string by replacing substrings "01" or "10" with "1" and "0" respectively. Examples: Input: S = "0110"Ou
4 min read
Most frequent character in a string after replacing all occurrences of X in a Binary String
Given a string S of length N consisting of 1, 0, and X, the task is to print the character ('1' or '0') with the maximum frequency after replacing every occurrence of X as per the following conditions: If the character present adjacently to the left of X is 1, replace X with 1.If the character prese
15+ min read
Minimize flips to make binary string as all 1s by flipping characters in substring of size K repeatedly
Given a binary string S of size N and an integer K, the task is to find the minimum number of operations required to make all characters as 1s in the binary string by flipping characters in the substring of size K. If it is not possible to do so, then print "-1". Examples: Input: S = "00010110 ", K
7 min read