Beautiful Binary String

Sort by

recency

|

859 Discussions

|

  • + 0 comments

    Here is solution in python, java, c++ and c programming - https://programmingoneonone.com/hackerrank-beautiful-binary-string-problem-solution.html

  • + 0 comments
    function beautifulBinaryString(b: string): number {
        // Write your code here
        let number_of_steps = 0;
        
        function finder(str: string){
            let substring_index = str.indexOf('010');
            if(substring_index === -1){
                return
            }
            number_of_steps++;
            if(substring_index + 3 >= str.length){
                return
            }
            finder(str.slice(substring_index + 3));
        }
        finder(b);
        return number_of_steps;
    }
    
  • + 0 comments
    int beautifulBinaryString(string b) {
        int ptrn = 0;
        
        for (int i = 0; i<b.size(); i++){
            string sub = b.substr(i, 3);
            
            if(sub=="010"){
                ptrn++;
                i+=2;
            }
        }
        
        return ptrn;
    }
    
  • + 0 comments
    # Beautiful Binary String
    def beautiful_binary_string(b):
        return b.count('101')
    
  • + 0 comments

    🧠 Problem: Beautiful Binary String

    This function counts the minimum number of operations required to make a binary string "beautiful" by replacing occurrences of '010' with '011'.

    def beautifulBinaryString(b):
        count = 0
        ans = 0
        while count != 1:
            a = b.find('010')
            if a >= 0:
                b = b[:a+2] + '1' + b[a+3:]
                ans += 1
                count += 0
            else:
                count += 1
        return ans
    

    🧪 Example Usage

    s = '0101010'
    print(beautifulBinaryString(s))  # Output: 2
    

    ✅ Notes:

    • The find('010') method locates the first occurrence of the pattern.
    • The string is modified to break the pattern by changing the last '0' to '1'.
    • The loop continues until no '010' is found.