Program to find maximum binary string after change in python


Suppose we have a binary string. We can apply each of the following operations any number of times −

  • If the number contains a substring "00", we can replace it with "10".

  • If the number contains a substring "10", we can replace it with "01".

Then we have to find the maximum binary (based on its numeric value) string we can get after any number of operations.

So, if the input is like s = "001100", then the output will be 111011, because we can transfer them like (00)1100 -> 101(10)0 -> 1010(10) -> 10(10)01 -> 100(10)1 -> 1(00)011 -> 111011.

To solve this, we will follow these steps −

  • length := size of s
  • zeros := number of 0s in s
  • if zeros < 2, then
    • return s
  • s := remove all '1's from left of s
  • leading_ones := length - size of s
  • leading_ones := leading_ones + zeros - 1
  • trailing_ones := length - leading_ones - 1
  • answer_left := leading_ones number of 1s
  • answer_right := trailing_ones number of 1s
  • answer_left concatenate 0 concatenate answer_right and return

Example

Let us see the following implementation to get better understanding −

def solve(s):
   length = len(s)
   zeros = s.count('0')
   if zeros < 2:
      return s
   s = s.lstrip('1')
   leading_ones = length - len(s)
   leading_ones += zeros - 1
   trailing_ones = length - leading_ones - 1
   answer_left = '1' * leading_ones
   answer_right = '1' * trailing_ones
   return ''.join([answer_left, '0', answer_right])

s = "001100"
print(solve(s))

Input

"001100"

Output

111011

Updated on: 06-Oct-2021

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements