Computer >> Computer tutorials >  >> Programming >> Javascript

Finding minimum flips in a binary string using JavaScript


Monotonically Increasing String:

A string of '0's and '1's is monotonically increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)

Problem

We are required to write a JavaScript function that takes in a binary string, str, as the first and the only argument.

We can flip any ‘0’ to ‘1’ or any ‘1’ to ‘0’ present in the string. Our function should return the minimum number of flips to make S monotonically increasing.

For example, if the input to the function is

Input

const str = '00110';

Output

const output = 1;

Output Explanation

Because if we flip the last ‘0’ to ‘1’, we will be left with the string ‘00111’.

Example

const str = '00110';
const countFlips = (str = '') => {
   const map = {}
   const helper = (index, prev) => {
      map[index] = map[index] || {}
      if (map[index][prev] !== undefined) {
         return map[index][prev]
      }
      if (index >= str.length) {
         return 0
      }
      if (prev === '0') {
         if (str[index] === '0') {
            map[index][prev] = Math.min(helper(index + 1, '0'), helper(index + 1, '1') + 1)
      } else {
         map[index][prev] = Math.min(helper(index + 1, '1'), helper(index + 1, '0') + 1)
      }
      } else if (str[index] === '0') {
         map[index][prev] = helper(index + 1, '1') + 1
      } else {
         map[index][prev] = helper(index + 1, '1')
      }
         return map[index][prev]
      }
   return helper(0, '0')
};
console.log(countFlips(str));

Output

1