Maximum count of unique index 10 or 01 substrings in given Binary string
Given a binary string str of length N, the task is to count the maximum number of adjacent pairs of form “01” or “10” that can be formed from the given binary string when one character can be considered for only one pair.
Note: Adjacent pair means pair formed using adjacent characters.
Input: str = “0101110”
Explanation: The three pairs are “01” at the starting first,
“01” starting at 2nd index (0 based indexing)
and “10” at the end of the string.
Notice 2 pairs can also be formed by using “10” from index 1 and “10” at last.
But that does not give the maximum number of adjacent pairs.
Input: str = “0011”
Input: str = “11”
Approach: This is a implementation based problem. Follow the steps mentioned here to solve the problem:
- Traverse string from left to right.
- Initialize count of pairs with 0 and consider the previous character as free.
- Run a loop from 1 to size of the string.
- Check if the previous character is opposite to the current character or not and also if it is free or not
- If yes then increment count of pairs and set the character as not free.
- Else continue the traversal in the loop considering the character as free.
- Print the count of pairs.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(1)