C++ Program to find minimum possible unlancedness of generated string T


Suppose we have a string S with possible characters '0', '1' or '?'. We want to make string T by replacing each occurrence of '?' with 0 or 1. The unbalancedness of T is like: maximum of the all absolute differences between number of occurrences of 0 and 1 in between lth and rth character in S where 0 <= l <= r < Size of S. We have to find the minimum possible unbalancedness of T.

So, if the input is like S = "0??0", then the output will be 2

To solve this, we will follow these steps −

Define a function check(), this will take S, x,
L := 0, R = x
B := true
for initialize i := 0, when i < size of S, update (increase i by 1), do:
   if S[i] is same as '0', then:
      decrease L and R by 1, each
   if S[i] is same as '1', then:
      increase L and R by 1, each
   if S[i] is same as '?', then:
      if L is same as R, then:
         B := false
         (decrease L by 1)
         (increase R by 1)
   if R is same as x + 1, then:
      if B is non-zero, then:
         (decrease R by 1)
      Otherwise
         R := R - 2
   if L < 0, then:
      if B is non-zero, then:
         (increase L by 1)
      Otherwise
         L := L + 2
   if L > R, then:
      return false
return true
From the main method, do the following
L := 1, R := 1000000
while L <= R, do:
   Mid := floor of (L + R)/2
      if check(S, Mid), then:
         R := Mid - 1
      Otherwise
         L := Mid + 1
return R + 1

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool check(string S, int x) {
   int L = 0, R = x;
   bool B = true;
   for (int i = 0; i < S.size(); i++) {
      if (S[i] == '0')
         L--, R--;
      if (S[i] == '1')
         L++, R++;
      if (S[i] == '?') {
         if (L == R)
            B = false;
         L--;
         R++;
       }
       if (R == x + 1) {
          if (B)
             R--;
          else
             R -= 2;
      }
      if (L < 0) {
         if (B)
            L++;
         else
            L += 2;
      }
      if (L > R)
         return false;
   }
   return true;
}
int solve(string S) {
   int L = 1, R = 1000000;
   while (L <= R) {
      int Mid = L + R >> 1;
      if (check(S, Mid))
         R = Mid - 1;
      else
         L = Mid + 1;
   }
   return R + 1;
}
int main() {
   string S = "0??0";
   cout << solve(S) << endl;
}

Input

0??0

Output

2

Updated on: 25-Feb-2022

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements