FOR FREE YEAR SOLVED

Beautiful string

Back to Programming

Description

RAM has a binary string. i.e. string consists of 0’s and 1’s. we think a binary string is beautiful if and only if it does not contain the substring “010”. In one step, he can change a 0 to 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.

For Example:

If RAM has string b = 010. He can change any one element and have a beautiful string.

Example: b = “0100101010”

O/P: 3

Number of times ‘010’ occurring in string as a substring is 3.

So, we can change the string 3 times to make it beautiful string.

Algorithm

Let us understand what substring is:

S = “apple”

All substrings of S are

“apple”, “appl”, “app’, “ap”, “a”, “ “, “pple”, “ple”, “le”, “e”, “ppl”, “pp”, “pl”, “p”, “l”

If we can find the number of substrings “010” in the string. We will get our required answer i.e. changing these many times we can convert the string to beautiful string.

Find the number of substrings “010” in the string and return it

Code

Time Complexity: O(n)           /for the count function

Space Complexity: O(1)