# Check If every group of a is followed by a group of b of same length in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string s with only two characters a and b. We have to check whether every group of consecutive a's is followed by group of consecutive b's of equal length.

So, if the input is like s = "abaaabbbaabbaabbab", then the output will be True, as all groups are (ab), (aaabbb), (aabb), (aabb), (ab).

To solve this, we will follow these steps −

• a_count := 0, string_len := size of s
• i := 0
• while i < string_len, do
• while i < string_len and s[i] is 'a', do
• a_count := a_count + 1
• i := i + 1
• while i < string_len and s[i] is 'b', do
• a_count := a_count - 1
• i := i + 1
• if a_count is not 0, then
• return False
• return True

## Example

Let us see the following implementation to get better understanding −

Live Demo

def solve(s):
a_count = 0
string_len = len(s)
i = 0
while i < string_len:
while i < string_len and s[i] == 'a':
a_count += 1
i += 1
while i < string_len and s[i] == 'b':
a_count -= 1
i += 1
if a_count != 0:
return False
return True
s = "abaaabbbaabbaabbab"
print(solve(s))

## Input

"abaaabbbaabbaabbab"

## Output

True