Beautiful Binary String HackerRank Solution in C, C++, Java, Python

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.

For example, if Alice’s string is b=010 she can change any one element and have a beautiful string.

Function Description

Complete the beautifulBinaryString function in the editor below. It should return an integer representing the minimum moves required.

beautifulBinaryString has the following parameter(s):

  • b: a string of binary digits

Input Format

The first line contains an integer , the length of binary string.

The second line contains a single binary string .

Constraints

  • 1<=n<=100
  • .b[i] belongs to {0,1}

Output Format

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

Sample Input 0

7

0101010

 

Sample Output 0

2  

 

Beautiful Binary String HackerRank Solution in C

#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);
    int i=0,count=0;
    while(B[i]){
        if(B[i]=='0'&&B[i+1]=='1'&&B[i+2]=='0'){
         B[i+2]='1';
         count++;
        }
        i++;
    }
    printf("%d",count);
    return 0;
}

 

Beautiful Binary String HackerRank Solution in C++

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

char B[105];

int main(){
    int n;
    int ans=0;
    scanf("%d", &n);
    scanf("%s", 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;
}

 

Beautiful Binary String HackerRank Solution in Java

import java.io.*;
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(System.in);
        int n = in.nextInt();
        String B = in.next();
        
        int i = 0;
        int total = 0;
        while (i < B.length()-2) {
            if (B.substring(i,i+3).equals("010")) {
                total++;
                i+=3;
            } else {
                i++;
            }
        }
        System.out.println(total);
    }
}

 

Beautiful Binary String HackerRank Solution in Python

#!/bin/python

import sys


n = int(raw_input().strip())
B = raw_input().strip()

if '010' not in B:
    print 0
else:
    print B.count('010')

 

Beautiful Binary String HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

public class Solver
{
    public void Solve()
    {
        int n = ReadInt();
        var a = ReadToken().ToCharArray();

        int ans = 0;
        for (int i = 1; i + 1 < n; i++)
            if (a[i - 1] == '0' && a[i] == '1' && a[i + 1] == '0')
            {
                a[i + 1] = '1';
                ans++;
            }

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;

    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("game.in");
        //writer = new StreamWriter("game.out");
#endif
        try
        {
            new Solver().Solve();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#else
            Console.WriteLine(ex);
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read / Write

    private static Queue<string> currentLineTokens = new Queue<string>();

    private static string[] ReadAndSplitLine()
    {
        return reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public static string ReadToken()
    {
        while (currentLineTokens.Count == 0)
            currentLineTokens = new Queue<string>(ReadAndSplitLine());
        return currentLineTokens.Dequeue();
    }

    public static int ReadInt()
    {
        return int.Parse(ReadToken());
    }

    public static long ReadLong()
    {
        return long.Parse(ReadToken());
    }

    public static double ReadDouble()
    {
        return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
    }

    public static int[] ReadIntArray()
    {
        return ReadAndSplitLine().Select(x => int.Parse(x)).ToArray();
    }

    public static long[] ReadLongArray()
    {
        return ReadAndSplitLine().Select(x => long.Parse(x)).ToArray();
    }

    public static double[] ReadDoubleArray()
    {
        return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
    }

    public static int[][] ReadIntMatrix(int numberOfRows)
    {
        int[][] matrix = new int[numberOfRows][];
        for (int i = 0; i < numberOfRows; i++)
            matrix[i] = ReadIntArray();
        return matrix;
    }

    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows);
        int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = new int[numberOfRows];
            for (int j = 0; j < numberOfRows; j++)
                ret[i][j] = matrix[j][i];
        }
        return ret;
    }

    public static string[] ReadLines(int quantity)
    {
        string[] lines = new string[quantity];
        for (int i = 0; i < quantity; i++)
            lines[i] = reader.ReadLine().Trim();
        return lines;
    }

    public static void WriteArray<T>(IEnumerable<T> array)
    {
        writer.WriteLine(string.Join(" ", array.Select(aa => aa.ToString()).ToArray()));
    }

    public static void Write<T>(params T[] array)
    {
        WriteArray(array);
    }

    public static void WriteLines<T>(IEnumerable<T> array)
    {
        foreach (var a in array)
            writer.WriteLine(a);
    }

    #endregion
}

 

Attempt Beautiful Binary String Hackerrank Challenge

Link – https://www.hackerrank.com/challenges/beautiful-binary-string/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/closest-numbers-hackerrank-solution/

Leave a Comment