Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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_countto 0 and get the length of strings - Set index
ito 0 - While
iis less than string length:- Count consecutive
a's by incrementinga_count - Count consecutive
b's by decrementinga_count - If
a_countis not 0 after processing a group, return False
- Count consecutive
- 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
aencountered, increment the counter - For each
bencountered, 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.
