Open In App

Make S into an alternate binary string by replacing any character with 0 or 1 up to K times

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  1. Checking for validity, Whether conversion in alternating binary string is possible or not?
  2. Is it possible under at most K operations?
  3. 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);


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads