# C++ Program to find minimal sum of all MEX of substrings

Suppose we have a binary string S with n bits. Let an operation MEX of a binary string be the smallest digit among 0, 1, or 2 that does not occur in the string. For example, MEX(001011) is 2, because 0 and 1 occur in the string at least once, MEX(1111) is 0, because 0 is not present and 0 is minimum. From the given string S. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string. We have to find the minimal sum of MEX of all substring’s pieces can be?

## Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings.htm

So, if the input of our problem is like S = "01", then the output will be 1, because MEX(0) is 1, MEX(1) is 0, so sum is 1 + 0 = 1.

## Steps

To solve this, we will follow these steps −

count := (1 if S[0] is 0, otherwise 0)
for initialize i := 1, when S[i] is non-zero, update (increase i by 1), do:
if S[i] is same as '0' and S[i] is not equal to S[i - 1], then:
(increase count by 1)
return minimum of count and 2

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(string S){
int count = (S[0] == '0');
for (int i = 1; S[i]; i++)
if (S[i] == '0' && S[i] != S[i - 1])
count++;
return min(count, 2);
}
int main(){
string S = "01";
cout << solve(S) << endl;
}

## Input

"01"

## Output

1