Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Beautiful Binary String Solution

Yashwant Parihar, April 26, 2023May 6, 2023

In this post, we will solve HackerRank Beautiful Binary String Problem Solution.

Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn’t contain the substring “010”.
In one step, Alice can change a 0 to a 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.
Example
b = 010
She can change any one element and have a beautiful string.

nction Description

Complete the beautifulBinaryString function in the editor below.

beautifulBinaryString has the following parameter(s):

  • string b: a string of binary digits

Returns

  • int: the minimum moves required

Input Format

The first line contains an integer n, the length of binary string.
The second line contains a single binary string b.

Output Format

Print the minimum number of steps needed to make the string beautiful.

Sample Input 0

STDIN       Function
-----       --------
7           length of string n = 7
0101010     b = '0101010'

Sample Output 0

2  

Explanation 0:
In this sample, b = “0101010”
The figure below shows a way to get rid of each instance of “010”:

Make the string beautiful by changing 2 characters (b[2] and b[5]).

Sample Input 1

5
01100

Sample Output 1

0

Sample Case 1:
In this sample b = “01100”
Explanation 1
The substring “010” does not occur in b, so the string is already beautiful in 0 moves.

Sample Input 2

10
0100101010

Sample Output 2

3

Explanation 2

In this sample b = “0100101010” One solution is to change the values of b[2], b[5] and b[9] to form a beautiful string.

HackerRank Beautiful Binary String Problem Solution
HackerRank Beautiful Binary String Problem Solution

Beautiful Binary String C Solution

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n; 
    scanf("%d",&n);
    char* B = (char *)malloc(10240 * sizeof(char));
    scanf("%s",B);
    printf("%d\n", countSubstring(B, "010"));
    return 0;
}
 
int countSubstring(const char *str, const char *sub)
{
    int length = strlen(sub);
    if (length == 0) return 0;
    int count = 0;
    for (str = strstr(str, sub); str; str = strstr(str + length, sub))
        ++count;
    return count;
}

Beautiful Binary String C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    string s;
    int n,ans=0;
    cin>>n>>s;
    for(int i = 1;i<n-1;i++)
        if(s[i-1]=='0'&&s[i]=='1'&&s[i+1]=='0') s[i+1]='1', ans++;
    cout<<ans;
    return 0;
}

Beautiful Binary String C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Solution {

    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        string B = Console.ReadLine();
        int count = 0;

    for (int i = 0; i < n-2; i++){
        if (B[i] != '0'){
            continue;
        }
        if (i+2 < n && B.Substring(i, 3) == "010"){
            count++;
            i +=2;
        }
    }
    Console.WriteLine(count);
    }
}

Beautiful Binary String Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'beautifulBinaryString' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts STRING b as parameter.
     */

    public static int beautifulBinaryString(String b) {
    // Write your code here
        Pattern p = Pattern.compile("010");
        return (int)p.matcher(b).results().count();    
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        String b = bufferedReader.readLine();

        int result = Result.beautifulBinaryString(b);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Beautiful Binary String JavaScript Solution

'use strict';

function main() {
    input = input.split('\n').slice(1)[0];
    let steps = 0;
    if (input.length >= 3) {
        for (let i = 0; i < input.length - 2; i++) {
            if (input[i] + input[i + 1] + input[i + 2] === '010') {
                steps++;
                i += 2;
            }
        }
    }
    process.stdout.write(steps + '');
}

process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";

process.stdin.on('data', function (data) {
    input += data;
});

process.stdin.on('end', main);

if (process.argv[2] === 'test') {
    process.stdin.pause();
    input = `
    7
    0101010
    `.replace(/^\s+/mg, "").trim();
    process.stdout.write(`Input:\n${input}\n\nOutput:\n`);
    main();
}

Beautiful Binary String Python Solution

#!/bin/python3

import sys


n = int(input().strip())
B = input().strip()
bb = [i for i in B]
strn = "010"
c = 0
while True:
    a = B.find(strn)
    #print(a)
    if a >= 0:
        bb[a+2] = "1"
        #print(bb)
        B = ''.join(bb)
        #print(B)
        c += 1
    else:
        break
print(c)

Other Solutions

  • HackerRank Closest Numbers Problem Solution
  • HackerRank The Love-Letter Mystery Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes