Minimize replacement of bits to make the count of 01 substring equal to 10 substring
Given a binary string str. The task is to minimize the number of replacements of ‘0’ by ‘1’ or ‘1’ by ‘0’ to balance the binary string. A binary string is said to be balanced: “if the number of “01” substring = number of “10” substring”.
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: str = “101010”
Output: 1
Explanation: “01” = 2 & “10” = 3. So change the last character to ‘1’. The modified string will be “101011” or “001010”.Input: str = “0000100” // balanced, “01” = 1 & “10” = 1
Output: 0
Explanation: The string is already balanced.
Approach: One can notice that “the balanced binary string will always have it’s first character equals to last character of string.”
Only one step is required to balance it, that is s.back() = s.front(). See the proof provided below
Proof:
Above Approach can be proved by using Principal of Mathematical Induction.
NOTE: In below proof, all the cases where first character equals to last character are considered.for n = 0 —> empty string “” // count of “10” = 0 & count of “01” = 0
for n = 1 —> “0” or “1” // count of “10” = 0 & count of “01” = 0
for n = 2 —> “00” or “11” // count of “10” = 0 & count of “01” = 0
for n = 3—> “000” // count of “10” = 0 & count of “01” = 0
or “111” // count of “10” = 0 & count of “01” = 0
or “010” // count of “10” = 1 & count of “01” = 1
or “101” // count of “10” = 1 & count of “01” = 1Hence, By the the principal of mathematical induction it will be true for every n, where n is a natural number.
Below is the implementation of the above approach.
C++
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to count the minimum// number of replacementsint minimizeReplacements(string str){ unordered_map<string, int> count; string temp; // Loop to count the minimum number // of replacements required for (int i = 0; i < str.length() - 1; i++) { temp = str.substr(i, 2); count[temp]++; } return abs(count["10"] - count["01"]);} // Driver codeint main(){ // Given string string str = "101010"; cout << minimizeReplacements(str) << endl; return 0;} |
1
Time Complexity: O(N)
Auxiliary Space: O(1)

