

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Finding minimum deletions in string in JavaScript
- Finding minimum absolute difference within a Binary Search Tree in JavaScript
- Minimum Number of Flips to Convert Binary Matrix to Zero Matrix in C++
- Finding mistakes in a string - JavaScript
- Number of flips to make binary string alternate - Set 1 in C++
- Swapping string case using a binary number in JavaScript
- Finding Mode in a Binary Search Tree in JavaScript
- Finding missing letter in a string - JavaScript
- Minimum Number of K Consecutive Bit Flips in C++
- Converting string to a binary string - JavaScript
- Interchanging a string to a binary string in JavaScript
- Finding shortest word in a string in JavaScript
- Finding hamming distance in a string in JavaScript
- Minimum flips in two binary arrays so that their XOR is equal to another array in C++.
- Finding second smallest word in a string - JavaScript
Advertisements