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

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).

Algorithm

To solve this, we will follow these steps ?

  • Initialize a_count to 0 and get the length of string s
  • Set index i to 0
  • While i is less than string length:
    • Count consecutive a's by incrementing a_count
    • Count consecutive b's by decrementing a_count
    • If a_count is not 0 after processing a group, return False
  • Return True if all groups are balanced

Example

Let us see the following implementation to get better understanding ?

def solve(s):
    a_count = 0
    string_len = len(s)
    i = 0
    
    while i < string_len:
        # Count consecutive 'a's
        while i < string_len and s[i] == 'a':
            a_count += 1
            i += 1
        
        # Count consecutive 'b's
        while i < string_len and s[i] == 'b':
            a_count -= 1
            i += 1
        
        # If counts don't match, return False
        if a_count != 0:
            return False
    
    return True

# Test the function
s = "abaaabbbaabbaabbab"
print(solve(s))
True

How It Works

The algorithm uses a counter approach:

  • For each a encountered, increment the counter
  • For each b encountered, decrement the counter
  • After processing each group pair, the counter should be zero
  • If the counter is non-zero after any group, the lengths don't match

Alternative Approach Using Regular Expressions

We can also solve this using regular expressions to match the pattern ?

import re

def solve_regex(s):
    # Pattern: one or more 'a's followed by same number of 'b's
    pattern = r'^(a+b+)*$'
    
    if not re.match(pattern, s):
        return False
    
    # Check if each 'a' group matches corresponding 'b' group
    groups = re.findall(r'a+|b+', s)
    
    for i in range(0, len(groups), 2):
        if i + 1 >= len(groups):
            return False
        if len(groups[i]) != len(groups[i + 1]):
            return False
    
    return True

s = "abaaabbbaabbaabbab"
print(solve_regex(s))
True

Conclusion

The counter-based approach efficiently checks if every group of a's is followed by an equal-length group of b's. The algorithm runs in O(n) time complexity with O(1) space complexity, making it optimal for this problem.

Updated on: 2026-03-25T15:01:00+05:30

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements