Beautiful Binary String Hackerrank problem solution

Beautiful Binary String Hackerrank

Alice has a binary string, B, of length n. 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.

Input Format

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


1<=n<=100 Each character in B{0,1}. Output Format

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

Sample Input 0


Sample Output 0

Sample Input 1


Sample Output 1

Sample Input 2


Sample Output 2


Sample Case 0:

In this sample, B=”0101010″

The figure below shows a way to get rid of each instance of “010”:

Beautiful Binary String Hackerrank

Because we were able to make the string beautiful by changing 2 characters (B2 and B5), we print 2.

Sample Case 1:

In this sample, B=”01100″

The substring “010” does not occur in B, so the string is already beautiful and we print 0.

#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int main(){
    int n;
    int ans=0;
    string B;
    for(int i=2; B[i]; i++){
        if(B[i-2] == '0' && B[i-1] == '1' && B[i] == '0') B[i] = '1', ans++;
    printf("%d", ans);
    return 0;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(;
        int n = in.nextInt();
        String B =;
        System.out.println((B.length() - B.replaceAll("010", "").length())/3);
n = input()
B = list(raw_input())
cnt = 0
for i in xrange(n):
    if B[i: i + 3] == ['0', '1', '0']:
        B[i + 2] = '1'
        cnt += 1
print cnt

A web developer(Front end and Back end), and DBA at Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me

Leave a reply:

Your email address will not be published.